I want my function to take a closure as an argument, which takes a PartialOrd (or any other trait, this is just an example) as an argument and I want to be able to call that closure with a any type that implements PartialOrd in my function. Something along the lines of this:
fn my_func(cmp: fn(impl PartialOrd, impl PartialOrd) -> bool) {
cmp(3, 5);
}
But of course this does not work because impl Trait is not valid in closure signatures. (I don't see why but I guess it not implemented yet.) So I tried something like this:
fn my_func<T: PartialOrd>(cmp: fn(T, T) -> bool) {
cmp(3, 5);
}
This also doesn't compile because (I guess) T is determined by the caller and I'm just passing i32 and it might be different that what the caller is intended to call.
So, how do I go about this? My main purpose is to do something like this:
fn my_func(cmp: fn(impl PartialOrd, impl PartialOrd) -> bool) {
if some_condition {
cmp(type1_instance, type1_instance_2);
} else {
cmp(type2_instance, type2_instance_2);
}
}
Both type1 and type2 implements PartialEq.
To make it more concerete, I'm using chrono library and want to write something like this:
fn compare_dates(d1: DateTime, d2: DateTime, cmp: fn(impl PartialOrd, impl PartialOrd) -> bool) -> bool {
if some_condition {
cmp(d1, d2)
} else {
cmp(d1.date(), d2.date())
}
}
compare_dates(
Utc.date(2000 10, 11).and_hour(0,0,0),
Utc.date(2000 10, 12).and_hour(0,0,0),
PartialOrd::lt)
Note: DateTime::date() does not return DateTime, it returns a different Date type.