Rust has a feature that allows you to branch the way you compare objects through the and traits .PartialEq
Eq
Deducing from the documentation, the only difference between the two would be that it Eq
adds the reflexive property to the formula.
But then, are there cases of objects that implement PartialEq
with custom code and that require Eq
?
That is, if creating my own implementation of PartialEq
to compare both objects, in what case would it be advisable and even mandatory to use Eq
?
#[derive(PartialEq, Eq)]
enum Color {
Red,
Blue,
}
#[derive(PartialEq, Eq)]
enum Category {
Hatchback,
Truck,
}
struct Car {
color: Color,
category: Category,
}
impl PartialEq for Car {
fn eq(&self, other: &Self) -> bool {
self.category == other.category
}
}
fn main() {
let my_hatch = Car {
color: Color::Blue,
category: Category::Hatchback,
};
let my_truck = Car {
color: Color::Red,
category: Category::Truck,
};
println!("Are those two cars equals? {}", my_hatch == my_truck);
}
It is as you have described it,
PartialEq
andEq
they only differ in the reflexive property (that is,Siendo T: PartialEq, T == T no se cumple necesariamente
). This looks easy with the following enum:In this case, two errors of the type
Error::BadRequest { code }
can be perfectly compared and will be equal to themselves if the code and the variant are the same, butError::UnknownError
not, since two errors of that type do not know if they are equal since their origin is unknown. you can't claim that they are the same type as each other even if they are structurally the same for the computer.Another example is
f32
, which is the very example that they give you in the documentation, all numbers are comparable to each other, unlessNan
it is the result of,0/0
for example, or the root of a negative number, but in no case can you say that they are the same number since itsqrt(-1) == sqrt(-2)
is false, that in rust it would be represented for the compiler like thisNaN == NaN
andNaN
structurally it is the same but logically it is different.In your example, since there are no ambiguities , the logical thing to do (but not necessary if you do not use the reflexive property) is to also add the
Eq
, but it is not something to worry too much about, many people always add both unless they find some logical problem when doing so.