gpt4 book ai didi

datetime - 使用 `serde::Serialize` 和 `Option`

转载 作者:行者123 更新时间:2023-12-04 16:24:39 27 4
gpt4 key购买 nike

尝试序列化时 Option<chrono::DateTime<Utc>> 我遇到了一个错误:

error[E0308]: mismatched types
--> src/main.rs:39:14
|
39 | #[derive(Serialize, Debug)]
| ^^^^^^^^^ expected struct `DateTime`, found enum `std::option::Option`
|
= note: expected reference `&DateTime<Utc>`
found reference `&'__a std::option::Option<DateTime<Utc>>`
= note: this error originates in a derive macro (in Nightly builds, run with -Z macro-backtrace for more info)
代码 ( Playground ):
use chrono::{serde::ts_seconds, DateTime, NaiveDate, Utc};
use serde::Serialize;

fn main() {
let test_struct = TestStruct {
a: 2.45,
date: Some(DateTime::from_utc(
NaiveDate::from_ymd(2000, 1, 1).and_hms(1, 1, 1),
Utc,
)),
};
let string = serde_json::to_string(&test_struct).unwrap();
println!("default: {}", string);

#[derive(Serialize, Debug)]
struct TestStruct {
pub a: f32,
#[serde(with = "ts_seconds")]
pub date: Option<DateTime<Utc>>,
}
}
看着 chrono::ts_seconds serde_with我不知道该往哪里推进。
我真的很感激这方面的任何帮助。

最佳答案

Chrono 已有 Option<DateTime<Utc>> 的功能,即 chrono::serde::ts_seconds_option .

#[derive(Serialize, Debug)]
struct TestStruct {
pub a: f32,
#[serde(with = "ts_seconds_option")]
pub date: Option<DateTime<Utc>>,
}
serde_with 的解决方案看起来像这样:
#[serde_as]
#[derive(Serialize, Debug)]
struct TestStruct {
pub a: f32,
#[serde_as(as = "Option<DurationSeconds<i64>>")]
pub date: Option<DateTime<Utc>>,
}

关于datetime - 使用 `serde::Serialize` 和 `Option<chrono::DateTime>`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67803619/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com