Json: error[E0283]: type annotations required: cannot resolve `T: serde::Deserialize<'de>`

Created on 28 Jul 2018  路  2Comments  路  Source: serde-rs/json

Hi, I got a compile error while trying to deserialize a strong type struct called ApiResponse, see below:

use serde::de::DeserializeOwned;

#[derive(Deserialize, Debug)]
pub struct ApiResponse<T: DeserializeOwned> {
    pub code: u32,
    pub data: T,
    pub message: String,
}

My REST API response has a fixed format which seems like to this:

{
  "code": 200,
  "data": {}, // "data" could be a objcet or list
  "message" : "success"
}

That is why I need an ApiResponse struct which keep data as a generic type to deserialize every possible response. For example the type T could be those types:

#[derive(Serialize, Deserialize, Debug)]
pub struct TagList {
    pub tags: Vec<String>,
}

// or 

#[derive(Serialize, Deserialize, Debug)]
pub struct Post {
    pub title: String,
    pub author: String,
    pub tag: String,
}

then I can deserialize ApiResponse\ or ApiResponse\, but I get such a compile error:

error[E0283]: type annotations required: cannot resolve `T: serde::Deserialize<'de>`
  --> src/api.rs:14:10
   |
14 | #[derive(Deserialize, Debug)]
   |          ^^^^^^^^^^^
15 | pub struct ApiResponse<T: DeserializeOwned> { 
   |
   = note: required by `serde::Deserialize`

Did I do something wrong? How to fix this issue? Any comment is welcome, thanks. 馃槃

support

Most helpful comment

You should not have trait bounds like T: DeserializeOwned on a data structure. See https://github.com/rust-lang-nursery/rust-clippy/issues/1689 for discussion about using trait bounds in this way.

The correct way to write this struct would be:

#[derive(Deserialize, Debug)]
pub struct ApiResponse<T> {
    pub code: u32,
    pub data: T,
    pub message: String,
}

All 2 comments

You should not have trait bounds like T: DeserializeOwned on a data structure. See https://github.com/rust-lang-nursery/rust-clippy/issues/1689 for discussion about using trait bounds in this way.

The correct way to write this struct would be:

#[derive(Deserialize, Debug)]
pub struct ApiResponse<T> {
    pub code: u32,
    pub data: T,
    pub message: String,
}

Thank you @dtolnay ! This works like a charm! 馃憤

Was this page helpful?
0 / 5 - 0 ratings

Related issues

VictorKoenders picture VictorKoenders  路  6Comments

mnacamura picture mnacamura  路  6Comments

generalelectrix picture generalelectrix  路  4Comments

jaredforth picture jaredforth  路  4Comments

harindaka picture harindaka  路  4Comments