2

I am working with the chrono library, and do not know how to define a struct field that is a vector of DateTime<Tz: TimeZone> structs with a TimeZone trait instead of a concrete type.

I.e, I can do:

use chrono::{DateTime, TimeZone, Utc}; // 0.4.11

pub struct ItemSchedule {
    pub times: Vec<Box<DateTime<Utc>>>,
}

When I try to use a trait object:

use chrono::{DateTime, TimeZone, Utc}; // 0.4.11

pub struct ItemSchedule {
    pub times: Vec<Box<DateTime<dyn TimeZone>>>,
}

I get an error:

error[E0191]: the value of the associated type `Offset` (from trait `chrono::offset::TimeZone`) must be specified
 --> src/lib.rs:4:37
  |
4 |     pub times: Vec<Box<DateTime<dyn TimeZone>>>,
  |                                     ^^^^^^^^ help: specify the associated type: `TimeZone<Offset = Type>`

Looking at the code, the TimeZone trait has an associated type called Offset, which has to implement a trait called Offset. I also get errors if I attempt to specify this the type declaration.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • I meant to answer your question but also got caught up in the type errors when trying to get dynamic dispatch working. In case you only want to store times belonging to the same timezone in an `ItemSchedule`, plain old static dispatch should work: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=ea602947e22114c9c9ca5ac8cad309c4 However, that's probably not what you wanted. – Danilo Bargen May 18 '20 at 21:36
  • I think a decent workaround is to convert everything to UTC, regardless of the original timezone, but I feel that this should be possible – stillearningsomething May 18 '20 at 22:04
  • 1
    I filed an issue related to this: "How to store TimeZone in Arc?" https://github.com/chronotope/chrono/issues/432 . – M. Leonhard Jun 11 '20 at 00:23

0 Answers0