Trait Model

Source
pub trait Model: Send + Sync {
    type Id: Send;

    // Required method
    fn get_id(&self) -> Option<Self::Id>;

    // Provided method
    fn has_id(&self) -> bool { ... }
}
Expand description

Trait for defining unique identification methods for database models.

The Model trait provides a standardized way to handle identification of database models, with built-in support for collections and wrapper types like Vec, Option, and Result.

§Type Parameters

  • Id: The associated type representing the identifier type for the model.

§Examples

Basic implementation for a user model:

struct User {
    id: i32,
    name: String,
}

impl Model for User {
    type Id = i32;

    fn get_id(&self) -> Option<Self::Id> {
        Some(self.id)
    }
}

Working with collections of models:



let users = vec![
    User { id: 1, name: String::from("Alice") },
    User { id: 2, name: String::from("Bob") }
];

// Get IDs for all users in the vector
let ids = users.get_id(); // Returns Some(vec![Some(1), Some(2)])

Handling optional models:


let maybe_user: Option<User> = Some(User { id: 1, name: String::from("Alice") });
let id = maybe_user.get_id(); // Returns Some(1)

let no_user: Option<User> = None;
let id = no_user.get_id(); // Returns None

§Implementation Notes

The trait provides automatic implementations for:

  • Vec<M>: Returns a vector of optional IDs
  • Option<M>: Propagates the inner model’s ID
  • Result<M, E>: Returns the ID from Ok variants, None for Err

All implementations use #[inline] for optimal performance in tight loops or when working with large collections of models.

Required Associated Types§

Source

type Id: Send

The type used for model identification

Required Methods§

Source

fn get_id(&self) -> Option<Self::Id>

Returns the model’s identifier if available

§Returns
  • Some(Id) - If the model has an identifier
  • None - If the model has no identifier

Provided Methods§

Source

fn has_id(&self) -> bool

Implementations on Foreign Types§

Source§

impl<K, V> Model for BTreeMap<K, V>
where K: Ord + Clone + Send + Sync, V: Model + Send + Sync,

Source§

type Id = BTreeMap<K, Option<<V as Model>::Id>>

Source§

fn get_id(&self) -> Option<Self::Id>

Source§

impl<K, V> Model for HashMap<K, V>
where K: Eq + Hash + Clone + Send + Sync, V: Model + Send + Sync,

Source§

type Id = HashMap<K, Option<<V as Model>::Id>>

Source§

fn get_id(&self) -> Option<Self::Id>

Source§

impl<M> Model for Option<M>
where M: Model + Send + Sync,

Source§

type Id = <M as Model>::Id

Source§

fn get_id(&self) -> Option<Self::Id>

Source§

impl<M> Model for Vec<M>
where M: Model + Send + Sync,

Source§

type Id = Vec<Option<<M as Model>::Id>>

Source§

fn get_id(&self) -> Option<Self::Id>

Source§

impl<M, E> Model for Result<M, E>
where M: Model + Send + Sync, E: Send + Sync,

Source§

type Id = <M as Model>::Id

Source§

fn get_id(&self) -> Option<Self::Id>

Implementors§