rustoperator-overloadingcomparison-operatorsfloating-point-comparison

How to tell rust to do all float comparisons using a given lib by default?


I would like to have all float comparisons done with float_cmp::approx_eq (for example), but keep using the equality comparison operator == for it. How do I achieve this?

impl PartialEq for f32 {
    fn eq(&self, other: &Self) -> bool {
        approx_eq!(f32, *self, *other)
    }
}

Results in:

error[E0119]: conflicting implementations of trait `std::cmp::PartialEq` for type `f32`
error[E0117]: only traits defined in the current crate can be implemented for arbitrary types

Solution

  • This is not possible:

    I don't think there is a way to accomplish this and I'm not sure I'd suggest using it even if there were. This would affect all cases where float comparison is done, even deep in your dependencies that could end up causing problems. And this leaves little option to do non-approximate equality even if you explicitly wanted to.

    You should handle cases where you only want to consider approximate equality explicitly.