1
pub async fn create<T: Serialize>(form: &mut T, COLLECTION_NAME: &str) -> Result<T, ServiceError> {
    let collection = db::get_collection(COLLECTION_NAME).await?;

    let mut doc = db::encode(&form).unwrap();
    collection.insert_one(doc, None).await?;
    find(form.id.as_ref().unwrap(), COLLECTION_NAME).await
}

I'm trying to define a generic function of Type T. When I try to access the field from 'form' which is of type T.

I get the following error:

no field `id` on type `&mut T` 
pub struct Form {
    #[serde(rename = "_id")]
    pub id: Option<ObjectId>,
    pub name: String,
}

The generic type T will receive the following struct as a parameter. There can be multiple structs with id field

Suman Kumar
  • 150
  • 1
  • 2
  • 11
  • There is no way to make a "has field" constraint. You have to define a getter in the trait. Why is this generic anyway? – Sebastian Redl Sep 26 '20 at 19:33
  • The function will receive different structs as a parameter. All having the id field – Suman Kumar Sep 26 '20 at 19:34
  • How to define a getter in the trait? – Suman Kumar Sep 26 '20 at 19:35
  • I've read traits at least basics, but unable to find answer for this – Suman Kumar Sep 26 '20 at 19:41
  • A getter is just a function, does that help? – Sebastian Redl Sep 26 '20 at 19:43
  • I know about getters. But the thing is I'll have multiple structs with id field. So, I am confused, how to define a trait with getter which works for every structs. Any suggestions? – Suman Kumar Sep 26 '20 at 19:46
  • Perhaps something like [this](https://gist.github.com/d8c8058ee6a01cf801fea1f27e563c9d) (obviously untested) – trent Sep 26 '20 at 19:46
  • @trentcl Actually I don't have a single struct. I'll pass structs with different fields with `id` as a common field to the function input. – Suman Kumar Sep 26 '20 at 19:49
  • The trait requires the getter. Every struct must impl the trait and thus the getter. – Sebastian Redl Sep 26 '20 at 19:50
  • I understand that @SebastianRedl Can you share some insights on where I can find the solution? – Suman Kumar Sep 26 '20 at 19:51
  • Yes, you need to implement `Id` for all the structs that you want to pass as `T`. Generics in Rust are not fancy macros like C++ templates; they are type checked at declaration. You can't claim to be generic over any `T` and then *assume* that `T` has an `id` field. If you *want* a fancy macro, consider writing an actual macro instead of a generic function. – trent Sep 26 '20 at 20:03

0 Answers0