【问题标题】:rust: expected type parameter, found struct [duplicate]锈:预期的类型参数,找到结构[重复]
【发布时间】:2019-08-13 08:04:40
【问题描述】:

我已经编写了一些函数来计算各种 TimeZone 的 T 的一些日期时间(从 chrono)。这些函数的不同之处主要在于返回值的类型 DateTime<Utc>DateTime<Local> 等。 我想知道是否可以使用泛型来概括这一点

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,但我不知道该怎么做。如果有人可以帮助我,我将不胜感激。谢谢!

【问题讨论】:

    标签: generics struct types rust


    【解决方案1】:

    正如我正确理解的那样,您想创建一个通用函数来为不同的时区调用 ymd()

    下面是一个适用于这种情况的通用函数的工作示例:

    fn event<T: TimeZone>(s: T) -> DateTime<T> {
        s.ymd(2019,8,13).and_hms(17, 30, 0)
    }
    

    要调用函数,请使用:

    event::<Local>(Local);
    

    【讨论】:

    • 谢谢!这正是我所需要的!
    猜你喜欢
    • 2014-11-20
    • 2018-02-07
    • 2017-09-13
    • 1970-01-01
    • 1970-01-01
    • 2020-10-13
    • 2021-03-11
    • 1970-01-01
    相关资源
    最近更新 更多