方法存在,但不满足以下特征边界(泛型)



我有一个工作函数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是存在的(它确实存在,就像在第一个代码片段中一样(,但特征边界并不满足。如何指定使该编译绑定的缺失特征?

考虑到第一个代码段是编译的,而我只提取了与参数相同的类型,我猜这应该是可能的。

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

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

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

最新更新