Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If f32 is not Eq, why does this compile?

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?

like image 881
Dmitri Nesteruk Avatar asked Oct 27 '25 03:10

Dmitri Nesteruk


1 Answers

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:

  • it must be possible to retrieve a value with the same key as it was inserted with
  • if there is a hash collision, the implementation can still distinguish distinct keys using ==, 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.

like image 168
Peter Hall Avatar answered Oct 30 '25 06:10

Peter Hall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!