rustlifetimeserdeserde-json

How can I derive Deserialize for struct with generic types?


#[derive(Deserialize)]
struct S<'d, T>
  where T: Deserialize<'d>
{
  foo: T,
  other_field: String
}

The above code fails to compile, complaining unused lifetime parameter, but if I remove it, Deserialize would missing lifetime.

Can the above code be made correct without using phantom marker or DeserializeOwned?


Solution

  • The code works if you remove the where clause completely. The derive will add a T: Deserialize<'de> bound automatically for the derived Deserialize<'de> implementation.

    #[derive(Deserialize)]
    struct S<T> {
      foo: T,
      other_field: String
    }
    

    For Rust it is common to not restrict generic types at struct/enum declarations. The generic type is only restricted for impl blocks where the behavior is needed.