【发布时间】:2021-11-23 08:35:11
【问题描述】:
我有以下从 XML 文件反序列化的结构。
#[derive(Deserialize, Debug)]
pub struct RawItem {
id: String,
title: String,
description: Option<String>,
link: String,
image_link: String,
availability: String,
price: String,
}
到目前为止一切顺利,对象已正确反序列化。现在,我的 XML 数据略有变化,价格字段变为可选。我想在丢失时将价格回退到“0.0”,因此我使用了 serde 默认机制:
#[derive(Deserialize, Debug)]
pub struct RawItem {
id: String,
title: String,
description: Option<String>,
link: String,
image_link: String,
availability: String,
#[serde(default = "0.0")] // Added this new line
price: String,
}
由于某种原因,它失败并出现以下错误:
error: failed to parse path: "0.0"
--> /home/xxxxxx/xxxxx/xxxxx/xxxxxx/xxxx/xxxxx/src/xxxx_specifics.rs:81:20
|
81 | #[serde(default = "0.0")]
| ^^^^^
error[E0277]: the trait bound `xxxx_specifics::RawItem: Deserialize<'_>` is not satisfied
--> /home/xxxxxx/xxxxx/xxxxx/xxxxxx/xxxx/xxxxx/src/xxxx_specifics.rs:68:2
|
68 | #[serde(rename = "item")]
| ^ the trait `Deserialize<'_>` is not implemented for `xxxx_specifics::RawItem`
|
= note: required because of the requirements on the impl of `Deserialize<'_>` for `Vec<xxxx_specifics::RawItem>`
note: required by `next_element`
--> /home/xxxxx/serde-1.0.130/src/de/mod.rs:1703:5
|
1703 | / fn next_element<T>(&mut self) -> Result<Option<T>, Self::Error>
1704 | | where
1705 | | T: Deserialize<'de>,
| |____________________________^
error[E0277]: the trait bound `xxxx_specifics::RawItem: Deserialize<'_>` is not satisfied
--> /home/xxxxxx/xxxxx/xxxxx/xxxxxx/xxxx/xxxxx/src/xxxx_specifics.rs:68:2
|
68 | #[serde(rename = "item")]
| ^ the trait `Deserialize<'_>` is not implemented for `xxxx_specifics::RawItem`
|
= note: required because of the requirements on the impl of `Deserialize<'_>` for `Vec<xxxx_specifics::RawItem>`
note: required by `next_value`
--> /home/xxxx/serde-1.0.130/src/de/mod.rs:1842:5
|
1842 | / fn next_value<V>(&mut self) -> Result<V, Self::Error>
1843 | | where
1844 | | V: Deserialize<'de>,
| |____________________________^
For more information about this error, try `rustc --explain E0277`.
error: could not compile `inko_importer` due to 3 previous errors
serde 默认的任何原因都会因字符串上的简单默认值而失败?
【问题讨论】:
-
请注意,实际错误包含在错误消息的最第一行中:
failed to parse path: "0.0",其中“path”指的是由标识符组成的路径,这些标识符导致函数,如module::submodule::function_name。其余的只是意味着宏没有完成它的工作,因此,Deserialize特征没有在RawItem上实现,而你的代码的其余部分期望它是这样的。