We have impl<T> Trait for Vec<T>
, which can implement Trait
for all Vec<_>
. Can we have the same thing for a newtype struct (a tuple struct with only one value)? Like:
impl<T> Trait for T(SomeType) {}
Why?
In DDD, each aggregate root/entity has a type of Id
:
struct BookId(Uuid);
struct Book {
id: BookId,
// ...
}
struct LibraryId(Uuid);
struct Library {
id: LibraryId,
// ...
}
I think it is a natural way to do the modelling, but if you do that, it is hard to implement a trait for all types of ID. An example trait is the FromSql
and ToSql
traits in rust-postgres.
We have to do this instead:
impl ToSql for BookId {
to_sql_checked!();
accepts!(UUID);
fn to_sql(&self, ty: &Type, w: &mut Vec<u8>) -> Res<IsNull> {
self.to_id().to_sql(ty, w)
}
}
impl<'a> FromSql<'a> for BookId {
accepts!(UUID);
fn from_sql(_: &Type, raw: &[u8]) -> Res<BookId> {
let uuid = types::uuid_from_sql(raw)?;
Ok(BookId::new(Uuid::from_bytes(uuid)))
}
}
// same thing for LibraryId
Not that clean, eh? Is there any way to make the code cleaner?