typically
typically

Reputation: 3520

Method exists but the following trait bounds were not satisfied (generics)

I have a working function foo, which compiles without error:

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:

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. 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

Upvotes: 4

Views: 2161

Answers (1)

typically
typically

Reputation: 3520

I took a look at the impl block for DateTime. 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, {
    ...
}

Upvotes: 4

Related Questions