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 IDsOption<M>
: Propagates the inner model’s IDResult<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.