Определить переменную типа TimeZone

Следующее компилируется и работает нормально:

      use chrono_tz::Tz;
use chrono::{TimeZone, NaiveDate};
use arrow2::temporal_conversions::parse_offset;

fn my_func(tz: &str) -> (){
    let ndt = NaiveDate::from_ymd_opt(2018, 9, 28).unwrap().and_hms_opt(2, 30, 0).unwrap();
    match parse_offset(&tz) {
        Ok(time_zone) => {
            println!("converted: {:?}", time_zone.from_utc_datetime(&ndt));
        },
        Err(_) => match tz.parse::<Tz>() {
            Ok(time_zone) => {
                println!("converted: {:?}", time_zone.from_utc_datetime(&ndt));
            }
            Err(error) => panic!("Problem opening the file: {:?}", error)
        },
    };
}


fn main() {
    let time_zone = "Asia/Seoul";
    my_func(&time_zone);
}

Хотя заметил, что я делаю

      println!("converted: {:?}", time_zone.from_utc_datetime(&ndt));

дважды.

Я попытался провести рефакторинг

      use chrono_tz::Tz;
use chrono::{TimeZone, NaiveDate};
use arrow2::temporal_conversions::parse_offset;

fn my_func(tz: &str) -> (){
    let ndt = NaiveDate::from_ymd_opt(2018, 9, 28).unwrap().and_hms_opt(2, 30, 0).unwrap();
    let parsed_time_zone: TimeZone = match parse_offset(&tz) {
        Ok(time_zone) => {
            time_zone
        },
        Err(_) => match tz.parse::<Tz>() {
            Ok(time_zone) => {
                time_zone
            }
            Err(error) => panic!("Problem opening the file: {:?}", error)
        },
    };
    println!("converted: {:?}", parsed_time_zone.from_utc_datetime(&ndt));
}


fn main() {
    let time_zone = "Asia/Seoul";
    my_func(&time_zone);
}

и получаю длинную ошибку:

      error[E0782]: trait objects must include the `dyn` keyword
 --> src/main.rs:7:27
  |
7 |     let parsed_time_zone: TimeZone = match parse_offset(&tz) {
  |                           ^^^^^^^^
  |
help: add `dyn` keyword before this trait
  |
7 |     let parsed_time_zone: dyn TimeZone = match parse_offset(&tz) {
  |                           +++

error[E0191]: the value of the associated type `Offset` (from trait `TimeZone`) must be specified
 --> src/main.rs:7:27
  |
7 |     let parsed_time_zone: TimeZone = match parse_offset(&tz) {
  |                           ^^^^^^^^ help: specify the associated type: `TimeZone<Offset = Type>`

error[E0038]: the trait `TimeZone` cannot be made into an object
 --> src/main.rs:7:27
  |
7 |     let parsed_time_zone: TimeZone = match parse_offset(&tz) {
  |                           ^^^^^^^^ `TimeZone` cannot be made into an object
  |
  = note: the trait cannot be made into an object because it requires `Self: Sized`
  = note: for a trait to be "object safe" it needs to allow building a vtable to allow the call to be resolvable dynamically; for more information visit <https://doc.rust-lang.org/reference/items/traits.html#object-safety>

error[E0308]: mismatched types
 --> src/main.rs:9:13
  |
9 |             time_zone
  |             ^^^^^^^^^ expected trait object `dyn TimeZone`, found struct `FixedOffset`
  |
  = note: expected trait object `dyn TimeZone`
                   found struct `FixedOffset`

error[E0308]: mismatched types
  --> src/main.rs:13:17
   |
13 |                 time_zone
   |                 ^^^^^^^^^ expected trait object `dyn TimeZone`, found enum `Tz`
   |
   = note: expected trait object `dyn TimeZone`
                      found enum `Tz`

error: the `from_utc_datetime` method cannot be invoked on a trait object
   --> src/main.rs:18:50
    |
18  |     println!("converted: {:?}", parsed_time_zone.from_utc_datetime(&ndt));
    |                                                  ^^^^^^^^^^^^^^^^^
    |
   ::: /home/marcogorelli/.cargo/registry/src/github.com-1ecc6299db9ec823/chrono-0.4.23/src/offset/mod.rs:205:21
    |
205 | pub trait TimeZone: Sized + Clone {
    |                     ----- this has a `Sized` requirement

Some errors have detailed explanations: E0038, E0191, E0308, E0782.
For more information about an error, try `rustc --explain E0038`.
error: could not compile `tmp` due to 6 previous errors

Я пробовал предложение сделать

      let parsed_time_zone: dyn TimeZone = match parse_offset(&tz) {

но тогда все еще ошибки с

      error[E0191]: the value of the associated type `Offset` (from trait `TimeZone`) must be specified
 --> src/main.rs:7:31
  |
7 |     let parsed_time_zone: dyn TimeZone = match parse_offset(&tz) {
  |                               ^^^^^^^^ help: specify the associated type: `TimeZone<Offset = Type>`

Как я могу просто разобратьtzкакTimeZone, не уточняя, является ли этоTzилиFixedOffset, а затем использовать его в остальной части функции?

0 ответов

Другие вопросы по тегам