Compare structs for Equality
-
Eq
-
PartialEq
-
Each data type in Rust either implements Eq or PartialEq to allow users to check if two objects of the same type are equal using either the
==
operator or theeq
method. -
When creating a struct it does not automatically implement these traits, but we can add them.
-
Primitive data types such as
integers
andstrings
implement both Eq and PartialEq. -
float
on the other hand only implements PartialEq as a float can also be NaN that would break Eq. -
We can add the
Eq
trait to any struct and if all the elements of the struct implementEq
then we can add that too: -
It will automatically provide us with the possibility to use
==
oreq
(or!=
orne
for that matter) on the values of that type. -
However
Eq
is mostly just an indication to the compiler, the actual implementation is inPartialEq
so we need to add that too. -
In order for two objects of this type to be equal, all the fields have to be equal.
#[derive(PartialEq, Eq)] struct Thing { name: String, number: i32, } fn main() { let a = Thing { name: String::from("Foo"), number: 42, }; let b = Thing { name: String::from("Foo"), number: 42, }; let c = Thing { name: String::from("Foo1"), number: 42, }; println!("{}", a == b); println!("{}", a == c); // We cannot compare which is bigger as we have not implemented (or derived from) Ord or PartialOrd. // println!("{}", a < c); }
true
false