Serde Deserialize help

This example with Serialize works:

extern crate serde; // 1.0.70
#[macro_use]
extern crate serde_derive; // 1.0.70

pub trait MyTrait: serde::Serialize + std::fmt::Debug {}
impl <T: serde::Serialize + std::fmt::Debug> MyTrait for T {}

#[derive(Serialize)]
pub enum MyType<T>
    where T: MyTrait
{
    Xxx(T)
}

fn main() {
    let _ = MyType::Xxx(12);
}

but almost same example with Deserialize doesn’t:

extern crate serde; // 1.0.70
#[macro_use]
extern crate serde_derive; // 1.0.70

pub trait MyTrait: serde::de::DeserializeOwned + std::fmt::Debug {}
impl <T: serde::de::DeserializeOwned + std::fmt::Debug> MyTrait for T {}

#[derive(Deserialize)]
pub enum MyType<T>
    where T: MyTrait
{
    Xxx(T)
}

fn main() {
    let _ = MyType::Xxx(12);
}

error:

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

Please help needed. Thnak you.

Data structures generally should never have type parameter bounds on them. The enum would be written:

#[derive(Deserialize)]
pub enum MyType<T> {
    Xxx(T)
}

with the T: MyTrait bound present only on impl blocks that require the behavior of that trait.

impl<T: MyTrait> MyType<T> {
    /* ... */
}

See rust-lang-nursery/rust-clippy#1689 for discussion of trait bounds on data structures.

1 Like

Thank you, very much. That helped!