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 theeqmethod. -
When creating a struct it does not automatically implement these traits, but we can add them.
-
Primitive data types such as
integersandstringsimplement both Eq and PartialEq. -
floaton the other hand only implements PartialEq as a float can also be NaN that would break Eq. -
We can add the
Eqtrait to any struct and if all the elements of the struct implementEqthen we can add that too: -
It will automatically provide us with the possibility to use
==oreq(or!=ornefor that matter) on the values of that type. -
However
Eqis mostly just an indication to the compiler, the actual implementation is inPartialEqso 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