optional
optional copied to clipboard
What exactly is the purpose of `OptEq`?
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.
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
andf64
don't supportEq
because of NaN and the floating point standards. But in this crateOptioned<f64>
with NaN as thef64
value is really theNone
value. And semantically twoNone
values are equal. - There is a blanket implementation for anything that implements
OptEq
to implementPartialEq
andEq
. You couldn't make that blanket implementation work forOptioned<f32>
orOptioned<f64>
if the constraint just relied onPartialEq
andEq
, but with the wrapper traitOptEq
, it does work. The wrapper trait allows the author to change the semantics ofPartialEq
andEq
forNoned<T>
to be different than their semantics forT
. - There is a similar and consistent approach taken for
PartialOrd
andOrd
. There you can see in the implementation ofOptOrd
that different inner functions are used for the floating and integer types. For the floating types a check for NaN is made (through theis_none
method), and then apartial_cmp
is used and unwrapped. The unwrap will never panic because we already checked for NaNs.
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.