在泛型结构上派生反序列化时无法解析 T: serde::Deserialize<'a>

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

我正在尝试编写一个派生 serde::Deserialize 的结构,但它还有一个应该派生 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() {}

我已经更改代码一段时间了,但我无法编译这个想法。我现在遇到的错误是:

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`

一般来说,you should not write Serde trait bounds on structs.

rustc --explain E0283 解释你的问题:

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

我发现使用 #[serde(bound()] 声明边界可以使示例编译:

#[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,
}

作为另一种解决方案,由于 T 是通用的并且可以作为参考,请考虑更改 Record 定义,以便 Serde 不需要更明确的指示:

#[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,
        }
    }
}