为什么Serde不能为只包含&Path的结构体派生Deserialize?

10

我试着为一个包含对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


使用 a: PathBuf - Boiethios
@FrenchBoiethios 谢谢你的推荐,但我在这个问题上可以执着一点 :) - Long
1
嗯,我查看了&'a str&'a PathDeserializeimpl,两种情况下所有内容看起来都一样,除了通过AsRef进行的类型转换,但这在PathVisitor的主体中,并且当出现此错误时应该已经进行了长时间的类型检查。看起来这甚至可能是生命周期推断中的一个错误。 - Jan Hudec
@JanHudec 感谢您的调查。我已经提交了错误报告以防万一。有一个故障的生命周期推断引擎听起来很可怕,所以希望不是这个问题 ^^ - Long
1个回答

12

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接