gpt4 book ai didi

rust - 为什么 Serde 不能为仅包含 &Path 的结构派生反序列化?

转载 作者:行者123 更新时间:2023-11-29 08:03:34 31 4
gpt4 key购买 nike

我尝试为包含对 Path 的引用的结构派生 serde::Deserialize。这会产生一条错误消息,如果您将 &'a Path 替换为 &'a str 则不会出现该错误消息。是什么导致了 #[derive(Deserialize)] 的不同行为?

Playground

#!/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/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com