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
This is not possible:
This trait implementation is in direct conflict with an existing implementation. There is no trait overriding mechanism. In the future you may be able to specialize a generic trait implementation, but this wouldn't be covered by that anyway.
Rust has "orphan rules" that govern what trait implementations you are allowed to define. In short, some part of the trait or type must be defined by the current crate. Neither PartialEq
and f32
are defined by you, so you cannot create this implementation.
The approx_eq!
macro from float_cmp
expands to code that uses ==
internally, so such implementation if it were allowed would cause infinite recursion.
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.