Cannot resolve T: serde::Deserialize<'a> when deriving Deserialize on a generic struct

折月煮酒 提交于 2020-02-21 21:55:52

问题


I'm trying to write a struct that derives serde::Deserialize but it also has a field that should derive serde::Deserialize:

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

use serde::{Deserialize, Serialize};

#[derive(PartialEq, Serialize, Deserialize)]
pub struct Record<'a, T>
where
    T: 'a + Serialize + Deserialize<'a>,
{
    id: &'a str,
    created_at: &'a str,
    created_by: Option<&'a str>,
    last_updated_at: Option<&'a str>,
    object: &'a T,
}

impl<'a, T> Record<'a, T>
where
    T: 'a + Serialize + Deserialize<'a>,
{
    pub fn new(
        id: &'a str,
        created_at: &'a str,
        created_by: Option<&'a str>,
        last_updated_at: Option<&'a str>,
        object: &'a T,
    ) -> Self {
        Record {
            id,
            created_at,
            created_by,
            last_updated_at,
            object,
        }
    }
}

fn main() {}

I've been changing the code for a while but I can't get this idea to compile. The error I'm getting at the moment is:

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

回答1:


In general, you should not write Serde trait bounds on structs.

rustc --explain E0283 explains your problem:

This error occurs when the compiler doesn't have enough information to unambiguously choose an implementation

I've found that using #[serde(bound()] for declaring the bounds makes the example compile:

#[derive(PartialEq, Serialize, Deserialize)]
pub struct Record<'a, T: 'a> {
    id: &'a str,
    created_at: &'a str,
    created_by: Option<&'a str>,
    last_updated_at: Option<&'a str>,
    #[serde(bound(deserialize = "&'a T: Deserialize<'de>"))]
    object: &'a T,
}

As another solution, as T is generic and may be a reference, consider changing the Record definition so Serde does not need more explicit indication:

#[derive(PartialEq, Serialize, Deserialize)]
pub struct Record<'a, T: 'a> {
    id: &'a str,
    created_at: &'a str,
    created_by: Option<&'a str>,
    last_updated_at: Option<&'a str>,
    object: T,
}

impl<'a, T: 'a> Record<'a, T> {
    pub fn new(
        id: &'a str,
        created_at: &'a str,
        created_by: Option<&'a str>,
        last_updated_at: Option<&'a str>,
        object: T,
    ) -> Self {
        Record {
            id,
            created_at,
            created_by,
            last_updated_at,
            object,
        }
    }
}


来源:https://stackoverflow.com/questions/49953960/cannot-resolve-t-serdedeserializea-when-deriving-deserialize-on-a-generic

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!