optional icon indicating copy to clipboard operation
optional copied to clipboard

What exactly is the purpose of `OptEq`?

Open LukasKalbertodt opened this issue 5 years ago • 2 comments

Hi there! I don't understand why there is the OptEq trait. Why can't this crate use PartialEq? I haven't found anything about this in the documentation.

LukasKalbertodt avatar Aug 23 '19 14:08 LukasKalbertodt

I think there is a couple reasons, but I'm not the crate owner/author so I can't speak to his original intentions.

  • f32 and f64 don't support Eq because of NaN and the floating point standards. But in this crate Optioned<f64> with NaN as the f64 value is really the None value. And semantically two None values are equal.
  • There is a blanket implementation for anything that implements OptEq to implement PartialEq and Eq. You couldn't make that blanket implementation work for Optioned<f32> or Optioned<f64> if the constraint just relied on PartialEq and Eq, but with the wrapper trait OptEq, it does work. The wrapper trait allows the author to change the semantics of PartialEq and Eq for Noned<T> to be different than their semantics for T.
  • There is a similar and consistent approach taken for PartialOrd and Ord. There you can see in the implementation of OptOrd that different inner functions are used for the floating and integer types. For the floating types a check for NaN is made (through the is_none method), and then a partial_cmp is used and unwrapped. The unwrap will never panic because we already checked for NaNs.

rnleach avatar Aug 23 '19 17:08 rnleach

If I remember correctly, I tried and failed to use PartialEq because of the coherence rules – I couldn't implement it for the floats because Rust cannot guarantee that those types won't ever implement the trait, so I needed a crate-local one.

llogiq avatar Aug 23 '19 20:08 llogiq