<分区>
我编写了一些函数来为各种 TimeZone 的 T 计算一些日期时间(来自 chrono)。这些函数的主要区别仅在于返回值的类型 DateTime<Utc>
。 , DateTime<Local>
ETC。
我想知道是否可以使用类似
fn event<T: TimeZone>() -> DateTime<T>
而不是单独的函数
fn event_local() -> DateTime<Local>
fn event_local() -> DateTime<Utc>
...
试图把它放在通用版本中,我得到了错误 “期望的类型参数,找到的结构” 我理解这个错误,但我想知道是否有办法规避它,因为用几乎相同的逻辑实现多个功能是很乏味的。
extern crate chrono;
use chrono::{TimeZone, DateTime, Local};
fn event() -> DateTime<Local> {
Local.ymd(2019,8,13).and_hms(17, 30, 0)
}
fn event_utc() -> DateTime<Local> {
Utc.ymd(2019,8,13).and_hms(17, 30, 0)
}
有效,而
fn event<T: TimeZone>() -> DateTime<T> {
Local.ymd(2019,8,13).and_hms(17, 30, 0)
}
没有编译出现上述错误。
查看问题 How to return an instance of a trait? ,建议使用 Box,但我不知道该怎么做。如果有人能帮助我,我将不胜感激。谢谢!