skip to content

Equality, Ordering and Hashing

PartialEq and PartialOrd allow incomparable values such as NaN, Eq and Ord promise total ones, and Hash must agree with Eq. Interviewers ask why f64 cannot be a HashMap key.

on this pageshow

questions

6

In Rust, why does `a == b` on two values of your own struct fail with E0369, and what do derive(PartialEq) and derive(Eq) add?

level: juniorimportance: must knowfreq 65%

answer

  1. no built-in structural equality
  2. == is a trait method call
  3. field by field, variant first
  4. a promise with nothing to implement

basics

~20 s

Rust has no automatic structural equality: == calls PartialEq::eq, so without an impl rustc reports E0369. derive(PartialEq) compares every field, plus the variant for enums; derive(Eq) adds no comparison logic, only the promise a == a, and needs every field Eq.

solid answer

~40 s

In Rust `a == b` is sugar for `PartialEq::eq(&a, &b)`, and a new struct implements no traits until you ask, so rustc stops with `` error[E0369]: binary operation `==` cannot be applied to type `Point` `` and suggests `#[derive(PartialEq)]`. The derive generates an `eq` that is true when all fields are equal; on an enum it also requires the same variant. `ne` comes free as `!eq`. `#[derive(Eq)]` adds no comparison logic: it tells the compiler and generic code that equality is reflexive, and the derive requires every field to be `Eq`, so a struct with an `f64` field can be `PartialEq` but not `Eq`. `assert_eq!` additionally needs `Debug` to print both sides on failure.

code

rust · 6 lines
rust
struct Point { x: i32, y: i32 }
fn main() {
    let a = Point { x: 1, y: 2 };
    let b = Point { x: 1, y: 2 };
    println!("{}", a == b);
}

go deeper

for a junior

Recall that == needs PartialEq, that E0369 means no impl exists, and that #[derive(PartialEq, Eq)] is the usual fix for a plain data struct.

for a middle

Explain what the derive generates for structs, enums and generic types, why Eq has nothing to implement, and why an f64 field blocks derive(Eq).

for a senior

Spot when a hand-written PartialEq leaves derived Hash or Ord disagreeing with it, and insist those impls be written from the same fields.

for a principal

Set the team default: derive PartialEq and Eq on value types whenever fields allow, and require a comment justifying any hand-written equality.

## Why == fails on a new struct In Rust, operators are trait method calls. `a == b` is rewritten to `PartialEq::eq(&a, &b)` and `a != b` to `PartialEq::ne(&a, &b)`. A struct you declare implements none of the standard traits until you derive or write them, so this fails: - rustc reports `` error[E0369]: binary operation `==` cannot be applied to type `Point` ``. - Its note says "an implementation of `PartialEq` might be missing for `Point`" and its help suggests `#[derive(PartialEq)]`. There is no fallback to comparing memory or addresses. If you want to know whether two references point at the same value, that is `std::ptr::eq`, a different question from value equality. ## What derive(PartialEq) generates The derive writes the obvious structural comparison, as documented on `PartialEq`: - **Structs:** two values are equal if all fields are equal, and not equal if any field differs. Each field is compared with its own `==`, so field types must implement `PartialEq`. - **Enums:** two values are equal if they are the **same variant** and all of that variant's fields are equal. `Shape::Circle(1)` never equals `Shape::Square(1)`. - **Generic types:** `#[derive(PartialEq)] struct Pair<T>` produces `impl<T: PartialEq> PartialEq for Pair<T>`, so `Pair<T>` is comparable exactly when `T` is. - **`ne`** is not generated separately; the trait's default `ne` returns `!self.eq(other)`, which keeps the two consistent. Because each field uses its own `==`, a derived `PartialEq` inherits the field's quirks. A struct holding an `f64` that is NaN is not equal to itself under the derived `eq`. ## Eq is a promise, not code `Eq` extends `PartialEq` with one law, **reflexivity**: `a == a` for every value. The compiler cannot check that law, which is why `Eq` has no methods to implement and why std calls a violation a *logic error* rather than something rustc rejects. | | `PartialEq` | `Eq` | |---|---|---| | Methods | `eq`, plus default `ne` | none to implement | | Laws | symmetric, transitive, `ne` consistent | all of those plus reflexive | | Derive requires | every field `PartialEq` | every field `Eq` | | Floats | implemented | not implemented (NaN) | | Typical consumers | `==`, `assert_eq!`, `contains` | hash-map keys, `Ord` (a supertrait) | So `#[derive(PartialEq, Eq)]` on a `Point { x: i32, y: i32 }` is free and correct, while `#[derive(Eq)]` on a struct with an `f64` field fails with ``error[E0277]: the trait bound `f64: Eq` is not satisfied``. The idiomatic default for a plain data type is to derive both whenever every field allows it, because `Eq` is what unlocks use as a hash-map key and is required before `Ord`. ## The derives that usually travel together A value type in Rust tends to collect a familiar attribute line, and each piece has a reason: 1. `Debug` — needed by `assert_eq!` and `assert_ne!`, which print both operands when the assertion fails. Without it you get `` error[E0277]: `Point` doesn't implement `Debug` ``, even though `PartialEq` is present. 2. `PartialEq`, then `Eq` when every field allows it. 3. `PartialOrd` and `Ord` if values need ordering; `Ord` requires `Eq` and `PartialOrd` first. 4. `Hash` if values become hash keys; derived together with `PartialEq` and `Eq`, the generated `Hash` automatically agrees with the generated equality. ## When to write PartialEq by hand Derive whenever "all fields equal" is what equality means. Write it yourself when the domain says otherwise, such as a `Book` whose identity is its ISBN regardless of format or a cache entry that should ignore a timestamp. The hand-written version is a single method: ```rust impl PartialEq for Book { fn eq(&self, other: &Self) -> bool { self.isbn == other.isbn } } ``` Two cautions come with that choice. First, if the type also derives `Hash`, `PartialOrd` or `Ord`, those derived impls still look at every field and will disagree with your narrower `eq`; implement them by hand from the same fields. Second, adding `impl Eq for Book {}` is your promise that the hand-written `eq` really is reflexive, symmetric and transitive. `PartialEq` also has a type parameter, `PartialEq<Rhs = Self>`, which is how std lets a `String` be compared with a `&str`. Implementing comparisons across your own types is possible, but keep it rare: each extra impl must stay consistent in both directions.

  • Why does assert_eq! still fail to compile on a struct that derives PartialEq?
    `assert_eq!` needs both operands to implement `Debug` as well as `PartialEq`, because on failure it prints the left and right values. Without `Debug`, rustc reports E0277 saying the type doesn't implement `Debug`. Adding `#[derive(Debug)]` fixes it.
  • If Eq has no methods to implement, what does deriving it actually change?
    It adds an `impl Eq` that satisfies bounds like `K: Eq` on hash-map keys and the `Eq` supertrait of `Ord`. The derive also checks at compile time that every field is `Eq`, so a struct holding `f64` is rejected. Run-time behaviour of `==` is unchanged; `eq` still comes from `PartialEq`.

  • Rust compares structs field by field automatically, like a built-in default.
  • When no PartialEq exists, == falls back to comparing memory addresses.
  • Eq adds a faster eq method that replaces the one from PartialEq.
  • Two enum values with equal fields are equal even across different variants.
  • assert_eq! only needs PartialEq on the compared type.
open as a page

In Rust, why can't a struct with f64 coordinate fields derive Eq, Ord or Hash, and how do you sort or key it?

level: middleimportance: must knowfreq 70%

basics

~20 s

Because NaN != NaN, f64 implements only PartialEq and PartialOrd, never Eq, Ord or Hash, so deriving them on a struct with f64 fields fails with E0277. Sort with sort_by(f64::total_cmp); key through a wrapper or an integer encoding.

open as a page

In Rust, how does #[derive(PartialOrd, Ord)] order struct values and enum variants, and why can reordering struct fields change sort results?

level: middleimportance: should knowfreq 45%

basics

~20 s

The derive compares struct fields lexicographically in top-to-bottom declaration order, and enum values by discriminant first (the top variant is smallest by default), then by fields. Moving a field changes which comparison runs first, so sort order silently changes.

open as a page

In Rust, how do you sort a Vec<Player> by score descending, then name ascending, using Ordering::then_with, sort_by_key or Reverse?

level: middleimportance: should knowfreq 50%

basics

~10 s

Use sort_by with b.score.cmp(&a.score).then_with(|| a.name.cmp(&b.name)), or sort_by_key returning (Reverse(p.score), p.name.clone()). Reverse flips one key; then_with runs the tie-breaker only when the first comparison is Equal.

open as a page

Since Rust 1.81, why can sorting floats with sort_by(|a, b| a.partial_cmp(b).unwrap_or(Ordering::Equal)) panic, and how do you write a comparator that cannot?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Rust 1.81's new sort implementations may panic when the comparator is not a total order. Treating NaN as Equal makes 1 == NaN == 5 while 1 < 5, breaking transitivity. Use f64::total_cmp, or keep Ord and its supertraits consistent.

open as a page

A Rust Username type has a case-insensitive hand-written PartialEq but derives Hash; why does a HashSet<Username> accept both "Alice" and "alice", and how do you fix it?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Hash must agree with Eq: k1 == k2 implies hash(k1) == hash(k2). The derived Hash feeds the exact bytes, so equal usernames usually hash apart and the set never compares them. Hash the normalised form eq compares.

open as a page