Почему Serde не может получить десериализацию для структуры, содержащей только путь &? - PullRequest
1 голос
/ 31 мая 2019

Я попытался получить serde::Deserialize для структуры, содержащей ссылку на Path. Это привело к сообщению об ошибке, которое не появляется, если вы замените &'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 ... На данный момент я думаю, что это ошибка .

1 Ответ

4 голосов
/ 31 мая 2019

Добавить атрибут в поле: #[serde(borrow)].Это будет указывать Серде, что он должен заимствовать стоимость.Вы должны предоставить этот атрибут для каждого заимствования, кроме &str и &[u8].

Источник: https://serde.rs/lifetimes.html#borrowing-data-in-a-derived-impl

...