[英]Write function that accepts two argument types but does the same thing
Here's my src/main.rs
file:这是我的src/main.rs
文件:
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
:和Cargo.toml
:
[package]
name = "tmp"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
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但是,我也可以将main
的最后一行更改为my_func(fixed_offset, ndt)
,并将my_func
中from_tz
的类型更改为FixedOffset
,代码仍然可以正常运行,打印
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
.在我的应用程序中,我不知道我会收到Tz
还是FixedOffset
。 Either way, I'd like to pass it to my_func
, and inside it do from_tz.from_local_datetime(&ndt)
.无论哪种方式,我都想将其传递给my_func
,并在其中执行from_tz.from_local_datetime(&ndt)
。
How can I let my_func
accept either Tz
or FixedOffset
?我怎样才能让my_func
接受Tz
或FixedOffset
?
In your case the method in question is of the traitTimeZone
so you can just accept a generic argument bound to that trait:在您的情况下,所讨论的方法具有TimeZone
特征,因此您可以只接受绑定到该特征的通用参数:
fn my_func<T: TimeZone>(from_tz: T, ndt: NaiveDateTime){
let res = from_tz.from_local_datetime(&ndt);
println!("res: {:?}", res);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.