我正在尝试编写一个派生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`
答案 0 :(得分:4)
一般来说,you should not write Serde trait bounds on structs。
rustc --explain E0283
解释了您的问题:
当编译器没有足够的信息来明确选择实现
时,会发生此错误
我发现使用#[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,
}
}
}