[英]Cannot resolve T: serde::Deserialize<'a> when deriving Deserialize on a generic struct
I'm trying to write a struct that derives serde::Deserialize
but it also has a field that should derive serde::Deserialize
: 我正在尝试编写一个派生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() {}
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`
In general, you should not write Serde trait bounds on structs . 通常, 您不应该在结构上编写Serde特征边界 。
rustc --explain E0283
explains your problem: rustc --explain E0283
解释你的问题:
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: 我发现使用#[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,
}
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: 作为另一种解决方案,由于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,
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.