Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
Folyd opened this issue Jul 28, 2018 · 2 comments
Labels

Comments

@Folyd
Copy link

Folyd commented Jul 28, 2018

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<TagList> or ApiResponse<Post>, 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. 😄

@dtolnay
Copy link
Member

dtolnay commented Jul 28, 2018

You should not have trait bounds like T: DeserializeOwned on a data structure. See rust-lang/rust-clippy#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,
}

@Folyd
Copy link
Author

Folyd commented Jul 28, 2018

Thank you @dtolnay ! This works like a charm! 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Development

No branches or pull requests

2 participants