[Tip] Generic function compare any Integer or Float type with 0

Previously, I asked a question, got a solution, and I search on web, find 2 good approaches.

  1. compare with T::default()
  2. compare with 2 multiply itself (@steffahn mentioned INFINITY will lead to same result)
  3. 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
    T: PartialEq + Default,
    a == T::default()

fn is_zero_sub<T>(a: T) -> bool
    T: PartialEq + Copy + Sub<Output = T>,
    a == a - a

fn is_zero_add<T>(a: T) -> bool
    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));

The way I've done this in the past was to do a - a, which would generate zero from whatever value I passed. That way it's not needed to be passed explicitly.

1 Like

a == a + a will also be true for positive and negative infinity for floats.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.