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\
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. 馃槃
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! 馃憤
Most helpful comment
You should not have trait bounds like
T: DeserializeOwnedon 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: