Previously, I asked a question, got a solution, and I search on web, find 2 good approaches.
- compare with T::default()
- compare with 2 multiply itself (@steffahn mentioned INFINITY will lead to same result)
- compare with itself sub itself (@jhpratt suggested)
use std::cmp::*;
use std::default::Default;
use std::ops::*;
fn is_zero_default<T>(a: T) -> bool
where
T: PartialEq + Default,
{
a == T::default()
}
fn is_zero_sub<T>(a: T) -> bool
where
T: PartialEq + Copy + Sub<Output = T>,
{
a == a - a
}
fn is_zero_add<T>(a: T) -> bool
where
T: PartialEq + Copy + Add<Output = T>,
{
a == (a + a)
}
fn main() {
println!("{}", is_zero_default(0));
println!("{}", is_zero_default(0.0));
println!("{}", is_zero_add(0));
println!("{}", is_zero_add(0.0));
println!("{}", is_zero_sub(0));
println!("{}", is_zero_sub(0.0));
}