2
votes

I want my trait to depend on Serde's:

pub trait MyTrait: Serialize + DeserializeOwned {}

#[derive(Serialize, Deserialize)]
pub struct MyStruct<T: MyTrait> {
    value: T,
}

impl MyTrait for i32 {}
impl MyTrait for MyStruct<i32> {}

(full code)

But I get this error:

error[E0283]: type annotations required: cannot resolve `T: serde::Deserialize<'de>`
  --> src/main.rs:11:21
   |
11 | #[derive(Serialize, Deserialize)]
   |                     ^^^^^^^^^^^
   |
   = note: required by `serde::Deserialize`

I have no idea what that means in this context. I don't understand how it relates to the info about E0283.

(I think that DeserializeOwned is what I want based on the Serde lifetimes info, but I can't find anything on "extending" traits, so I might be wrong).

1

1 Answers

4
votes

In general, avoid putting trait bounds on a struct. Instead, put the bounds on the impl block for the methods that need those bounds:

#[derive(Serialize, Deserialize)]
pub struct MyStruct<T> {
    value: T,
}

impl<T> MyStruct<T> where T: MyTrait {
    fn do_stuff(&self) {
        ...
    }
}

The difference in how the constraints are solved for a struct versus an impl block is a bit subtle, but suffice to say it's different and this change should make your code work as expected.