【问题标题】:Method exists but the following trait bounds were not satisfied (generics)方法存在但不满足以下特征界限(泛型)
【发布时间】:2021-01-17 15:45:09
【问题描述】:

我有一个工作函数foo,它编译没有错误:

use chrono;

fn foo() {
    let now = chrono::offset::Local::now();
    let mut buf = String::new();
    buf.push_str(&now.format("%Y/%m/%d").to_string());
}

当我尝试将now 变量提取到参数时:

fn foo<T: chrono::TimeZone>(now: chrono::DateTime<T>) {
    let mut buf = String::new();
    buf.push_str(&now.format("%Y/%m/%d").to_string());
}

编译时遇到这个错误:

error[E0599]: no method named `format` found for struct `chrono::DateTime<T>` in the current scope
   --> src/lib.rs:108:35
    |
108 |                 buf.push_str(&now.format("%Y/%m/%d").to_string());
    |                                   ^^^^^^ method not found in `chrono::DateTime<T>`
    |
    = note: the method `format` exists but the following trait bounds were not satisfied:
            `<T as chrono::TimeZone>::Offset: std::fmt::Display`

注释说 format 存在(确实存在,就像在第一个代码 sn-p 中一样),但不满足特征边界。如何指定要编译的缺失特征?

考虑到第一个 sn-p 编译并且我只提取与参数相同的类型,我猜想它应该是可能的。

相关计时文档:https://docs.rs/chrono/0.4.19/chrono/struct.DateTime.html

【问题讨论】:

    标签: rust traits


    【解决方案1】:

    我查看了 DateTime 的 impl 块。它具有以下形式的代码。我更新了函数的签名以匹配,现在它编译成功了。

    fn foo<T: chrono::TimeZone>(now: chrono::DateTime<T>)
    where
        T::Offset: std::fmt::Display, {
        ...
    }
    

    【讨论】:

      猜你喜欢
      • 2019-10-11
      • 1970-01-01
      • 2019-10-28
      • 1970-01-01
      • 2022-11-27
      • 2022-01-20
      • 2021-08-23
      • 2021-07-13
      • 2019-05-11
      相关资源
      最近更新 更多