为什么Serde无法为仅包含& Path的结构派生反序列化? [英] Why can Serde not derive Deserialize for a struct containing only a &Path?
问题描述
我试图为包含对Path
的引用的结构派生serde::Deserialize
.如果您将&'a Path
替换为&'a str
,则不会出现此错误消息.是什么导致#[derive(Deserialize)]
的不同行为?
I tried to derive serde::Deserialize
for a struct containing a reference to a Path
. This yielded an error message which doesn't occur if you replace &'a Path
with &'a str
. What causes the different behaviours of #[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
,则代码会编译...此时,我认为这是一个
Strangely enough, the code compiles if the struct contains both fields _a: &'a Path
and _b: &'a str
... At this point I think this is a bug.
推荐答案
向该字段添加属性:#[serde(borrow)]
.这表示要提示它应该借入该值.您必须为除&str
和&[u8]
以外的所有借项提供此属性.
Add an attribute to the field: #[serde(borrow)]
. That will indicate to serde that it should be borrowing the value. You must provide this attribute for every borrow except for &str
and &[u8]
.
来源: https://serde.rs/lifetimes. html#borrowing-data-in-a-derived-impl
这篇关于为什么Serde无法为仅包含& Path的结构派生反序列化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!