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

标签 rust serde

我尝试为包含对 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/

相关文章:

data-structures - 如何在结构内的 HashMap 中插入? [复制]

indexing - 有没有办法在 Rust 中用索引折叠?

javascript - Wasm-bindgen:u8数组作为输入和输出,生成的javascript具有不同的函数签名

rust - 函数返回 serde 反序列化类型时如何修复生命周期错误?

rust - serde:加速自定义枚举反序列化

xml - 无法使用 serde-xml-rs 解析带有可选元素的 XML

json - 使用 serde 漂亮地打印没有换行符的 JSON?

rust - Rust函数返回包含参数引用的对象可正常编译,但当&self包含在参数列表中时无法编译

rust - 为什么使用 Cell 来创建不可移动的对象?

rust - Visitor 特性如何只允许部分实现?