skip to content

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.