Create your own trait that defines the behavior of the various types:
trait Min {
fn min(self, other: Self) -> Self;
}
impl Min for u8 {
fn min(self, other: u8) -> u8 { ::std::cmp::min(self, other) }
}
impl Min for f32 {
fn min(self, other: f32) -> f32 { f32::min(self, other) }
}
fn foo<T>(v1: T, v2: T)
where T: Min
{
let new_min = Min::min(v1, v2);
}
As mentioned in other places, floating point comparisons are hard.
There's no one answer to what the result of min(NaN, 0.0)
should be, so it's up to you to decide. If you decide that NaN
is less than or greater than all other numbers, great! Maybe it's equal to zero! Maybe you should assert that there will never be a NaN
...