我尝试为包含对 Path
的引用的结构派生 serde::Deserialize
。这会产生一条错误消息,如果您将 &'a Path
替换为 &'a str
则不会出现该错误消息。是什么导致了 #[derive(Deserialize)]
的不同行为?
#!/bin/cargo script
//! ```cargo
//! [dependencies]
//! serde_derive="1.0"
//! serde="1.0"
//! ```
extern crate serde_derive;
use serde_derive::*;
#[derive(Deserialize)]
struct A<'a> {
a: &'a std::path::Path,
//a: &'a str,
}
fn main() {}
error[E0495]: cannot infer an appropriate lifetime for lifetime parameter `'de` due to conflicting requirements
--> src/main.rs:7:5
|
7 | a: &'a std::path::Path,
| ^
|
note: first, the lifetime cannot outlive the lifetime 'de as defined on the impl at 5:10...
--> src/main.rs:5:10
|
5 | #[derive(Deserialize)]
| ^^^^^^^^^^^
= note: ...so that the types are compatible:
expected _IMPL_DESERIALIZE_FOR_A::_serde::de::SeqAccess<'_>
found _IMPL_DESERIALIZE_FOR_A::_serde::de::SeqAccess<'de>
note: but, the lifetime must be valid for the lifetime 'a as defined on the impl at 6:10...
--> src/main.rs:6:10
|
6 | struct A<'a> {
| ^^
= note: ...so that the types are compatible:
expected _IMPL_DESERIALIZE_FOR_A::_serde::Deserialize<'_>
found _IMPL_DESERIALIZE_FOR_A::_serde::Deserialize<'_>
error[E0495]: cannot infer an appropriate lifetime for lifetime parameter `'de` due to conflicting requirements
--> src/main.rs:7:5
|
7 | a: &'a std::path::Path,
| ^
|
note: first, the lifetime cannot outlive the lifetime 'de as defined on the impl at 5:10...
--> src/main.rs:5:10
|
5 | #[derive(Deserialize)]
| ^^^^^^^^^^^
= note: ...so that the types are compatible:
expected _IMPL_DESERIALIZE_FOR_A::_serde::de::MapAccess<'_>
found _IMPL_DESERIALIZE_FOR_A::_serde::de::MapAccess<'de>
note: but, the lifetime must be valid for the lifetime 'a as defined on the impl at 6:10...
--> src/main.rs:6:10
|
6 | struct A<'a> {
| ^^
= note: ...so that the types are compatible:
expected _IMPL_DESERIALIZE_FOR_A::_serde::Deserialize<'_>
found _IMPL_DESERIALIZE_FOR_A::_serde::Deserialize<'_>
奇怪的是,如果结构包含两个字段 _a: &'a Path
和 _b: &'a str
代码编译......在这一点上我认为这是bug .
最佳答案
向字段添加属性:#[serde(borrow)]
。这将向 serde 表明它应该借用该值。您必须为除 &str
和 &[u8]
之外的每个借用提供此属性。
来源:https://serde.rs/lifetimes.html#borrowing-data-in-a-derived-impl
关于rust - 为什么 Serde 不能为仅包含 &Path 的结构派生反序列化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56394620/