Associated References types as Value Types

167 views Asked by At

This is a trait found in Diesel.

trait Identifiable {
    type Id;
    ...
}

This is a User model with derived impl of Identifiable.

#[derive(Identifiable)]
pub struct User {
    id: i32,
    first_name: String,
    last_name: String,
}

As per the docs, implementation of Identifiable is derived on the reference of the struct i.e. on &User. This is a trait to find with id defined on the Identifiable. The implementation on a User would be as follows.

trait Find<'a>: Sized where
    &'a Self: Identifiable,
    Self: 'a,
{
    fn find(id: <&'a Self as Identifiable>::Id) -> Result<Self, MyError>;
}

The impl of Find on a User.

impl<'a> Find<'a> for User {
    fn find(id: i32) -> Result<User, MyError> {
        let conn = ::establish_conn()?;
        Ok(users::table.find(id).get_result(&conn)?)
    }
} 

The error on compilation:

    fn find(id: i32) -> Result<Self> {
                ^^^ expected &i32, found i32

As I would like to find a user with an i32, the impl <&'a Self as Identifiable>::Id would refer to the id as &i32. I only want id to be a value not a reference type.

How can I define the type of id on find to be a value type when Identifiable is applied for reference type &User?

0

There are 0 answers