【发布时间】:2023-03-09 15:53:01
【问题描述】:
我有这些结构:
#[derive(Debug, Serialize, Deserialize)]
pub struct GGConf<'a> {
#[serde(alias = "ssh")]
#[serde(rename = "ssh")]
#[serde(default)]
#[serde(borrow)]
pub ssh_config: Option<SSHConfig<'a>>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct SSHConfig<'a> {
#[serde(alias = "privateKey")]
#[serde(rename = "privateKey")]
private_key: &'a str,
username: &'a str,
}
当我从 YAML 文件中读取数据时会发生反序列化:
let mut config: GGConf = serde_yaml::from_reader(file)?;
编译时出现错误:
error: implementation of `conf::_IMPL_DESERIALIZE_FOR_GGConf::_serde::Deserialize` is not general enough
--> src/conf.rs:50:34
|
50 | let mut config: GGConf = serde_yaml::from_reader(file)?;
| ^^^^^^^^^^^^^^^^^^^^^^^ implementation of `conf::_IMPL_DESERIALIZE_FOR_GGConf::_serde::Deserialize` is not general enough
|
::: /home/ninan/.cargo/registry/src/github.com-1ecc6299db9ec823/serde-1.0.98/src/de/mod.rs:524:1
|
524 | / pub trait Deserialize<'de>: Sized {
525 | | /// Deserialize this value from the given Serde deserializer.
526 | | ///
527 | | /// See the [Implementing `Deserialize`][impl-deserialize] section of the
... |
562 | | }
563 | | }
| |_- trait `conf::_IMPL_DESERIALIZE_FOR_GGConf::_serde::Deserialize` defined here
|
= note: `conf::GGConf<'_>` must implement `conf::_IMPL_DESERIALIZE_FOR_GGConf::_serde::Deserialize<'0>`, for any lifetime `'0`...
= note: ...but `conf::GGConf<'_>` actually implements `conf::_IMPL_DESERIALIZE_FOR_GGConf::_serde::Deserialize<'1>`, for some specific lifetime `'1`
我隐约明白 serde 反序列化也有一个生命周期 'de 并且编译器混淆了我为它指定的生命周期?如果我错了,请纠正我。
我目前如何正确地将 YAML 反序列化为两个结构? 有什么我在这里遗漏或误解的吗?
我查看了How do I resolve "implementation of serde::Deserialize is not general enough" with actix-web's Json type?,但我不能使用拥有的类型。我需要它是一个借来的类型。
我将尝试为此编写一个游乐场示例。
【问题讨论】:
-
很难回答您的问题,因为它不包含minimal reproducible example。我们无法分辨代码中存在哪些 crate(及其版本)、类型、特征、字段等。如果您尝试在Rust Playground 上重现您的错误,如果可能的话,这将使我们更容易为您提供帮助,否则在全新的 Cargo 项目中,然后在edit 您的问题中包含附加信息。您可以使用Rust-specific MRE tips 来减少您在此处发布的原始代码。谢谢!
标签: rust yaml deserialization lifetime serde