【发布时间】:2021-05-22 13:42:43
【问题描述】:
我正在尝试在SourceConfig 结构上实现serde::Deserialize,它包装了一个包含&'static str 的结构以及它自己的一些数据(playground):
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize)]
pub struct Config {
pub name: &'static str,
}
#[derive(Serialize, Deserialize)]
struct SourceConfig {
config: Config,
id: u32,
}
但这给了我一生的错误:
Compiling playground v0.0.1 (/playground)
error[E0495]: cannot infer an appropriate lifetime for lifetime parameter `'de` due to conflicting requirements
--> src/lib.rs:10:5
|
10 | config: Config,
| ^^^^^^
|
note: first, the lifetime cannot outlive the lifetime `'de` as defined on the impl at 8:21...
--> src/lib.rs:8:21
|
8 | #[derive(Serialize, Deserialize)]
| ^^^^^^^^^^^
note: ...so that the types are compatible
--> src/lib.rs:10:5
|
10 | config: Config,
| ^^^^^^
= note: expected `SeqAccess<'_>`
found `SeqAccess<'de>`
= note: but, the lifetime must be valid for the static lifetime...
note: ...so that the types are compatible
--> src/lib.rs:10:5
|
10 | config: Config,
| ^^^^^^
= note: expected `Deserialize<'_>`
found `Deserialize<'static>`
= note: this error originates in a derive macro (in Nightly builds, run with -Z macro-backtrace for more info)
error[E0495]: cannot infer an appropriate lifetime for lifetime parameter `'de` due to conflicting requirements
--> src/lib.rs:10:5
|
10 | config: Config,
| ^^^^^^
|
note: first, the lifetime cannot outlive the lifetime `'de` as defined on the impl at 8:21...
--> src/lib.rs:8:21
|
8 | #[derive(Serialize, Deserialize)]
| ^^^^^^^^^^^
note: ...so that the types are compatible
--> src/lib.rs:10:5
|
10 | config: Config,
| ^^^^^^
= note: expected `MapAccess<'_>`
found `MapAccess<'de>`
= note: but, the lifetime must be valid for the static lifetime...
note: ...so that the types are compatible
--> src/lib.rs:10:5
|
10 | config: Config,
| ^^^^^^
= note: expected `Deserialize<'_>`
found `Deserialize<'static>`
= note: this error originates in a derive macro (in Nightly builds, run with -Z macro-backtrace for more info)
error: aborting due to 2 previous errors
我尝试将#[serde(borrow)] 添加到SourceConfig 中的config,但这不起作用,因为Config 没有被借用。将其添加到Config 中的name 也不起作用。如何在SourceConfig 上正确实现Deserialize?
【问题讨论】:
标签: string rust deserialization borrow-checker serde