[英]Method exists but the following trait bounds were not satisfied (generics)
I have a working function foo
, which compiles without error:我有一个工作函数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());
}
When I try to extract the now
variable to a parameter:当我尝试将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());
}
I run into this error when compiling:我在编译时遇到这个错误:
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`
The note says that format
exists (it does, as in the first code snippet), but trait bounds aren't satisfied.注释说format
存在(它确实存在,就像在第一个代码片段中一样),但不满足特征边界。 How do I specify the missing trait bound to make this compile?如何指定缺少的特征绑定以进行编译?
I'm guessing it should be possible somehow, considering that the first snippet compiles and I'm only extracting the same type as a parameter.我猜这应该是可能的,考虑到第一个片段编译并且我只提取相同的类型作为参数。
Related chrono docs: https://docs.rs/chrono/0.4.19/chrono/struct.DateTime.html相关计时文档: https : //docs.rs/chrono/0.4.19/chrono/struct.DateTime.html
I took a look at the impl block for DateTime
.我查看了DateTime
的 impl 块。 It had code of the form below.它具有以下形式的代码。 I updated the function's signature to match, and it now compiles successfully.我更新了函数的签名以匹配,现在它编译成功。
fn foo<T: chrono::TimeZone>(now: chrono::DateTime<T>)
where
T::Offset: std::fmt::Display, {
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.