I have a generic type such as
impl<T: Eq> Eq for Complex<T> where T: Eq {}
For some reason, I'm able to make a Complex<f32> and have it compile and call eq() even though f32 does not (cannot) support full comparison (because nan!=nan).
How is this possible?
The eq method (which is called when you use the == operator) is part of the PartialEq trait, not Eq.
The Eq trait inherits all of its methods from PartialEq, adding none of its own, and its sole purpose is as a marker to assert that the == operator forms an equivalence relation on the implementing type.
Types like HashMap rely on Eq rather than PartialEq, so they can make logical guarantees - for example:
==, so one doesn't replace the other.It is always safe to derive an implementation of Eq because it will only be valid if all child fields are also Eq. However, if you implement Eq yourself, you need to make sure that the equivalence relation invariants are upheld.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With