【发布时间】:2021-12-01 12:34:37
【问题描述】:
在我当前的项目中,我试图将chrono::Duration 存储在配置结构中,偶尔会使用serde_json 对其进行序列化和反序列化。
不幸的是,Serialize 和 Deserialize 似乎没有为 chrono::Duration 实现。也就是说,chrono 表示它通过其可选功能之一支持serde。我尝试使用此方法,但现在编译器抱怨返回方法:
error[E0308]: mismatched types
--> src/config.rs:6:10
|
6 | #[derive(Serialize, Deserialize, Debug, Clone)]
| ^^^^^^^^^ expected struct `DateTime`, found struct `chrono::Duration`
|
= note: expected reference `&DateTime<Utc>`
found reference `&'__a chrono::Duration`
= note: this error originates in the derive macro `Serialize` (in Nightly builds, run with -Z macro-backtrace for more info)
error[E0308]: mismatched types
--> src/config.rs:6:21
|
6 | #[derive(Serialize, Deserialize, Debug, Clone)]
| ^^^^^^^^^^^ expected struct `chrono::Duration`, found struct `DateTime`
|
= note: expected struct `chrono::Duration`
found struct `DateTime<Utc>`
= note: this error originates in the macro `try` (in Nightly builds, run with -Z macro-backtrace for more info)
为什么会这样?我能做些什么来解决它?
这是有问题的代码:
use serde::{Serialize, Deserialize};
use chrono::{DateTime, Duration, Utc};
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Config {
pub dest_ip: String,
#[serde(borrow)]
pub include_paths: Vec<&'static std::path::Path>,
pub exclude_paths: Vec<&'static std::path::Path>,
#[serde(with = "chrono::serde::ts_seconds")]
pub time_between_checks: Duration,
}
另外,这里是 Cargo.toml 的相关部分:
serde_json = "1.0.72"
serde = { version = "1.0.130", features = ["derive"] }
chrono = { version = "0.4.19", features = ["serde"]}
【问题讨论】:
-
从 2017 年开始查看此问题 github.com/chronotope/chrono/issues/117
-
ts_seconds仅适用于DateTime实例。