Rust Reference ยท Core Traits
PartialEq and Eq traits
Reference for PartialEq and Eq in Rust: == and != operators, derive rules, why f64 is only PartialEq, comparing different types and writing manual impls.
PartialEq powers the == and != operators. You implement one method, eq, and ne comes for free. Eq is a marker trait on top of it that promises the equality is a full equivalence relation: reflexive (a == a), symmetric and transitive. Floating-point numbers are only PartialEq, because NaN != NaN.
Both are almost always derived. Eq is required for types used as HashMap keys, HashSet members, BTreeMap keys, and in assert_eq!-style code that wants a total comparison.
#[derive(PartialEq, Eq)] struct Id(u32);
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
pub trait PartialEq<Rhs = Self> where Rhs: ?Sized, { fn eq(&self, other: &Rhs) -> bool; fn ne(&self, other: &Rhs) -> bool { !self.eq(other) } } pub trait Eq: PartialEq<Self> { }
| Name | Description |
|---|---|
Rhs |
The type on the right of ==. It defaults to Self, but you can implement PartialEq<Other> to compare different types. |
other |
A reference to the right-hand value. a == b expands to PartialEq::eq(&a, &b). |
Returns: bool. Eq has no methods.
Usage notes
- Derive compares field by field in declaration order, and enums first by variant. All fields must implement
PartialEq(andEqforderive(Eq)). - Floats are
PartialEqonly. A struct that contains anf32orf64can derivePartialEqbut notEq, so it cannot be a hash key unless you wrap the float. - Laws to keep: symmetric (
a == bimpliesb == a), transitive, and, forEq, reflexive. Break them and collections such asHashMaporsortbehave unpredictably (but never unsafely). - Keep
Hashconsistent: ifa == bthenhash(a)must equalhash(b). When you writePartialEqby hand, writeHashby hand too, and compare the same fields. Aderive(Hash)next to a manualPartialEqis a classic bug. - Different-type comparisons exist in the standard library:
strwithString,Vec<T>with arrays and slices,&Awith&BwhenA: PartialEq<B>. Comparingi32withi64is a compile error, so convert first. assert_eq!needs bothPartialEqandDebugon the operands.- References compare by value.
&a == &bcompares the pointed-to values; usestd::ptr::eqfor identity. - Floats in tests: compare with a tolerance, not
==.
Related
PartialOrdandOrd,Hash,Clone,Debug- Lessons: Operator overloading, HashMap