Skip to content
Tutorials Center
My learning

Topics

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.

Rust
#[derive(PartialEq, Eq)]
struct Id(u32);

Try it

Rust Derived equality and floats

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.

Rust Manual and cross-type equality

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

Rust
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 (and Eq for derive(Eq)).
  • Floats are PartialEq only. A struct that contains an f32 or f64 can derive PartialEq but not Eq, so it cannot be a hash key unless you wrap the float.
  • Laws to keep: symmetric (a == b implies b == a), transitive, and, for Eq, reflexive. Break them and collections such as HashMap or sort behave unpredictably (but never unsafely).
  • Keep Hash consistent: if a == b then hash(a) must equal hash(b). When you write PartialEq by hand, write Hash by hand too, and compare the same fields. A derive(Hash) next to a manual PartialEq is a classic bug.
  • Different-type comparisons exist in the standard library: str with String, Vec<T> with arrays and slices, &A with &B when A: PartialEq<B>. Comparing i32 with i64 is a compile error, so convert first.
  • assert_eq! needs both PartialEq and Debug on the operands.
  • References compare by value. &a == &b compares the pointed-to values; use std::ptr::eq for identity.
  • Floats in tests: compare with a tolerance, not ==.