Write function that accepts two argument types but does the same thing


Here’s my src/main.rs file:

use chrono_tz::Tz;
use chrono::FixedOffset;
use chrono::{NaiveDateTime, TimeZone, NaiveDate};

fn my_func(from_tz: Tz, ndt: NaiveDateTime){
    let res = from_tz.from_local_datetime(&ndt);
    println!("res: {:?}", res);

fn main() {
    let area_location: Tz = "UTC".parse().unwrap();
    let hour = 3600;
    let fixed_offset: FixedOffset = FixedOffset::east_opt(5 * hour).unwrap();
    let ndt = NaiveDate::from_ymd_opt(2038, 1, 19).unwrap().and_hms_opt(3, 14, 08).unwrap();
    my_func(area_location, ndt)

and Cargo.toml:

name = "tmp"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

chrono = "0.4.23"
chrono-tz = "0.8.1"
regex = "1.7.1"

The code runs fine and prints

res: Single(2038-01-19T03:14:08UTC)

However, I can also change the last line of main to my_func(fixed_offset, ndt), and change the type of from_tz in my_func to FixedOffset, and the code will still run just fine, printing

res: Single(2038-01-19T03:14:08+05:00)

In my application, I don’t know whether I’ll receive a Tz or a FixedOffset. Either way, I’d like to pass it to my_func, and inside it do from_tz.from_local_datetime(&ndt).

How can I let my_func accept either Tz or FixedOffset?

>Solution :

In your case the method in question is of the trait TimeZone so you can just accept a generic argument bound to that trait:

fn my_func<T: TimeZone>(from_tz: T, ndt: NaiveDateTime){
    let res = from_tz.from_local_datetime(&ndt);
    println!("res: {:?}", res);

Leave a ReplyCancel reply