skip to content

Standard Library Traits

A handful of std traits define how values convert, compare, print, overload operators and get defaults. Interviewers expect you to know their contracts and when to derive them.

on this pageshow

explore

questions

26

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, after you write `impl From<Celsius> for Fahrenheit`, why does `let f: Fahrenheit = c.into();` also compile?

level: juniorimportance: must knowfreq 70%

basics

~20 s

Core has a blanket impl, Into<U> for T where U: From<T>, so implementing From<Celsius> for Fahrenheit gives Celsius an into() that calls Fahrenheit::from. The compiler only needs the target type, here from the let annotation.

open as a page

What does #[derive(Default)] generate for a Rust struct, and when does rustc refuse to compile it?

level: juniorimportance: must knowfreq 65%

basics

~20 s

It generates an impl Default whose default() calls Default::default() on every field, giving 0, false, empty strings and collections, and None. rustc rejects the derive with E0277 when any field's type does not implement Default.

open as a page

In Rust, why can a `Money` struct use `#[derive(Debug)]` while its `Display` implementation must be written by hand?

level: juniorimportance: must knowfreq 80%

basics

~20 s

Debug is the developer view, which rustc can generate mechanically from the type name and every field. Display is the user-facing text, a design choice only the author can make, so std ships no derive for it.

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

Why do Rust's guidelines say to implement `From` rather than `Into`, yet to write generic bounds as `T: Into<U>`?

level: middleimportance: must knowfreq 60%

basics

~20 s

Implementing From gives Into for free through core's blanket impl, while implementing Into gives no From. Bounds use Into for the reverse reason: T: Into<U> accepts every From-based conversion plus any type that only implements Into.

open as a page

Rust has no constructors, so how should new(), Default and a constructor returning Result divide the work of creating a value?

level: middleimportance: must knowfreq 55%

basics

~20 s

Constructors are ordinary associated functions: new is the conventional primary one, and Default gives the argument-free value, matching an empty new. When input can be invalid, new returns Result or Option, and the type skips Default unless a valid default exists.

open as a page

In Rust, which reference conversions does deref coercion perform automatically, where does it apply, and which conversion does it never perform?

level: middleimportance: must knowfreq 60%

basics

~20 s

Where the expected reference type is known, rustc applies Deref repeatedly: &T becomes &U when T: Deref<Target = U>, &mut T becomes &mut U through DerefMut, and &mut T becomes &U. A shared reference never becomes mutable.

open as a page

In Rust, what must a `Meters` type implement for `"12.5m".parse::<Meters>()` to compile, and what does `parse` return?

level: juniorimportance: should knowfreq 50%

basics

~10 s

Meters must implement std::str::FromStr, choosing an associated Err type and writing from_str(&str) returning Result<Self, Self::Err>. str::parse::<F>() just calls F::from_str, so it returns Result<Meters, Meters's Err type>.

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

Why does Rust's `std::fs::File::open` take `P: AsRef<Path>`, and when is `AsRef<str>` worth it over `&str`?

level: middleimportance: should knowfreq 45%

basics

~20 s

AsRef<Path> lets File::open accept &str, String, &Path, PathBuf and OsString, and as_ref() turns each into a &Path cheaply; deref coercion cannot turn a &str into a &Path. AsRef<str> pays off only when callers pass owned strings by value.

open as a page

How do you build a Rust `Email` newtype with `TryFrom<String>` so that no unvalidated string can ever become an `Email`?

level: middleimportance: should knowfreq 55%

basics

~20 s

Keep Email's String field private and implement TryFrom<String> for Email with an associated Error type; try_from validates and returns Result, TryInto comes free, and a From<String> impl must not exist, since rustc rejects the pair with E0119.

open as a page

How do you derive Default for a Rust enum such as LogLevel, and which rules does the #[default] attribute enforce?

level: middleimportance: should knowfreq 40%

basics

~10 s

Mark exactly one unit variant with #[default] and derive Default; default() returns that variant. Stable since Rust 1.62, it rejects a missing mark (E0665), two marks, a variant carrying data, or a #[non_exhaustive] variant.

open as a page

In Rust format strings, how do fill, alignment, width and precision combine, and why is `{price.cents}` rejected while `{price}` compiles?

level: middleimportance: should knowfreq 50%

basics

~20 s

After the colon comes fill, alignment, sign, #, 0, width, precision and type, in that order. Since Rust 1.58 a placeholder may capture a bare variable name, but field access, method calls and arithmetic are rejected.

open as a page

Why does Rust's standard library tell you to implement `Display` rather than `ToString`, and what does `money.to_string()` actually call?

level: middleimportance: should knowfreq 40%

basics

~20 s

std has a blanket impl<T: Display + ?Sized> ToString for T, so implementing Display gives to_string() for free. A hand-written ToString on a Display type conflicts with it (E0119), and ToString alone cannot be used with {}.

open as a page

In Rust, how do you make `a + b`, `a += b`, `-a` and `2.0 * a` compile for a `Vector3` type, and why does `a + b` move `a`?

level: middleimportance: should knowfreq 50%

basics

~20 s

Each operator is a std::ops trait: Add (with an Output type) for +, AddAssign for +=, Neg for unary minus, and Mul<Vector3> for f32 for 2.0 * a. Add::add takes self by value, so a non-Copy operand moves.

open as a page

In Rust, how do you make `grid[(row, col)]` read and write cells of a `Grid` type, and why must `Index::index` return a reference?

level: middleimportance: should knowfreq 35%

basics

~10 s

Implement std::ops::Index<(usize, usize)> with an Output type and fn index(&self, idx) -> &Output, plus IndexMut for writes. grid[i] is sugar for *grid.index(i), so index must lend out data the grid already owns.

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

In Rust, `Borrow<str>` and `AsRef<str>` share a method signature, so why may a case-insensitive name type implement only `AsRef<str>`?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Borrow adds a contract AsRef lacks: Eq, Ord and Hash of the borrowed view must match the owned value's, because maps look keys up through it. A case-insensitive key compares differently from str, so Borrow<str> would make lookups silently miss.

open as a page

For a Rust ServerConfig with a dozen optional settings, why use a builder instead of new() with Option parameters, and how should the builder be shaped?

level: seniorimportance: should knowfreq 45%

basics

~20 s

A builder replaces positional Some/None arguments with named, chained setters and one terminal build() that validates settings together and returns Result. Setters take and return self by value or &mut self, and #[must_use] warns when a configured builder is discarded.

open as a page

A Rust `Money` type implements `Display` with `write!`, yet `format!("{:>14}", price)` prints no padding — why, and how do you fix the impl?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Width, fill and alignment are carried by the Formatter, and a write! inside fmt formats fresh arguments that ignore them. Build the text and call f.pad(&text), or forward the Formatter to an inner value's Display::fmt.

open as a page

A Rust `Grid` newtype implements `Deref` and `DerefMut` to its `Vec<f32>` to reuse Vec's methods; why do `grid.clone()`, `grid.len()` and `grid.push(9.0)` misbehave?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Deref is not inheritance. Method calls fall through to Vec, so clone() returns a Vec<f32>, len() counts cells rather than rows, and DerefMut lets push() break the rows-times-cols invariant. The wrapper's traits and guarantees do not transfer.

open as a page

As a Rust lead, what rule would you set for when a newtype may implement `Deref` or `DerefMut`, and what should the team use instead?

level: principalimportance: should knowfreq 25%

basics

~20 s

Allow Deref only on wrappers that behave transparently as their target: pointer-like, cheap, infallible, adding no invariant. Allow DerefMut only when every mutation of the target keeps the wrapper valid. Otherwise use explicit accessors, AsRef and real trait impls.

open as a page

When a derived `Debug` is wrong for a Rust `Matrix`, how do `debug_struct`, `debug_list` and `finish_non_exhaustive` keep both `{:?}` and `{:#?}` working?

level: seniorimportance: nice to knowfreq 25%

basics

~10 s

Formatter's debug builders write the braces, commas and indentation themselves and switch to multi-line output when the alternate flag is set, so {:#?} keeps working. finish_non_exhaustive prints .. to mark fields deliberately left out.

open as a page