skip to content

Operators and Deref

Operators are traits in std::ops, and Deref lets a wrapper act like what it wraps through deref coercion. Interviewers ask why Deref is not for inheritance.

on this pageshow

questions

5

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%

answer

  1. the compiler inserts deref calls
  2. only where the expected type is known
  3. three directions, one forbidden
  4. generic parameters see no coercion

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.

solid answer

~40 s

Deref coercion happens at coercion sites, where the target type is already fixed: function arguments, `let` with an explicit type, struct fields, return values. rustc inserts as many `Deref::deref` calls as it needs, a count decided at compile time, so `&Box<String>` reaches `&str` through `&String`. There are three directions: `&T` to `&U` when `T: Deref<Target = U>`, `&mut T` to `&mut U` when `T: DerefMut`, and `&mut T` to `&U`. The fourth, `&T` to `&mut U`, never happens; rustc reports E0308 with "types differ in mutability", because a shared borrow cannot prove it is the only one. Coercion also does not apply when a parameter is generic: for `fn dump<T: Debug>(x: &T)`, `T` is inferred as the type you passed, and rustc checks that type's own impls without looking through `Deref`.

code

rust · 12 lines
rust
fn shout(s: &str) -> usize { s.len() }
fn scale(v: &mut [f32]) { for x in v { *x *= 2.0; } }
fn main() {
    let owned = String::from("thrust");
    let boxed: Box<String> = Box::new(String::from("drag"));
    let mut speeds: Vec<f32> = vec![1.0, 2.0];
    println!("{}", shout(&owned));       // &String -> &str
    println!("{}", shout(&boxed));       // &Box<String> -> &String -> &str
    scale(&mut speeds);                  // &mut Vec<f32> -> &mut [f32]
    let total: &[f32] = &mut speeds;     // &mut Vec<f32> -> &[f32]
    println!("{total:?}");
}

go deeper

for a junior

Recall that &String passes where &str is expected and &Vec<T> where &[T] is, because both types implement Deref.

for a middle

Explain the three directions, why & never becomes &mut, how chains like &Box<String> to &str resolve, and which places count as coercion sites.

for a senior

Diagnose the generic-parameter case behind an E0277, choose between &*x and a turbofish, and know each implicit deref call should be cheap and infallible.

for a principal

Treat Deref on your own types as public API: every caller inherits silent conversions, so the coverage of coercion is a reason to implement Deref rarely.

## What deref coercion is A **coercion** is a type change the compiler performs implicitly. **Deref coercion** is the one driven by the `Deref` and `DerefMut` traits in `std::ops`. If a type `T` implements `Deref<Target = U>`, then wherever the program supplies a `&T` but the context needs a `&U`, rustc inserts a call to `Deref::deref` for you. The `Deref` documentation lists the effects: `*v` on such a value means `*Deref::deref(&v)`, values of type `&T` coerce to `&U`, and `T` behaves as if it had every `&self` method of `U`. That last effect is method lookup, a related but separate mechanism (covered with references and method calls). This answer is about the reference conversions. ## The three directions | You have | Context needs | Allowed when | Example | |---|---|---|---| | `&T` | `&U` | `T: Deref<Target = U>` | `&String` to `&str` | | `&mut T` | `&mut U` | `T: DerefMut<Target = U>` | `&mut Vec<f32>` to `&mut [f32]` | | `&mut T` | `&U` | `T: Deref<Target = U>` | `&mut Vec<f32>` to `&[f32]` | | `&T` | `&mut U` | never | rejected with E0308 | The missing fourth direction follows from the borrow rules. A `&mut` is exclusive, so downgrading it to a shared reference is always sound. A `&T` may be one of many shared references, so upgrading it would let two parts of the program alias a mutable value. Given `fn scale(v: &mut [f32])` and `scale(&speeds)`, rustc 1.99.1 reports **E0308 mismatched types** with the label "types differ in mutability". Declaring `speeds` as `let mut` does not help; the argument expression `&speeds` is still a shared reference, and you must write `&mut speeds`. ## Chains are resolved at compile time rustc keeps dereferencing until the types match, so coercions chain: 1. `&Box<String>` becomes `&String` through `Box`'s `Deref`. 2. `&String` becomes `&str` through `String`'s `Deref<Target = str>`. 3. The call `shout(&boxed)` with `fn shout(s: &str)` therefore compiles with no explicit conversion. The Rust Book stresses that the number of `deref` calls is decided at compile time, so there is no run-time search. Each step is still an ordinary call to your `deref` method, which is why std's documentation says a `Deref` implementation should be cheap and "should never unexpectedly fail": the caller never sees the call in the source. ## Where it applies and where it does not The Rust Reference names the **coercion sites**, places where the expected type is explicit or propagated from explicit types without inference: - arguments of function and method calls (the receiver of a method call follows separate lookup rules); - `let` statements with a type annotation, and `static` and `const` items; - struct, union and enum-variant field initialisers; - function results, whether the block's final expression or a `return`; - the right-hand side of an assignment; - sub-expressions of those sites, such as array elements, tuple fields and the final expression of a block. It does **not** apply where the type is still being inferred: - **Generic parameters.** For `fn dump<T: Debug>(value: &T)`, passing `&grid` infers `T = Grid`. rustc then requires `Grid: Debug`; it never tries `Vec<f32>: Debug` just because `Grid` derefs to `Vec<f32>`. The result is **E0277**, "`Grid` doesn't implement `Debug`". Write `dump(&*grid)` or `dump::<Vec<f32>>(&grid)` to pick the target explicitly. - **`let` without an annotation.** `let r = &owned;` is a `&String`; nothing pushes it to `&str` until it meets a site that asks. - **Trait implementations.** A wrapper that derefs to a type does not implement that type's traits. ## Explicit alternatives When coercion does not fire, or when you want the conversion visible, use an explicit form: - `&*owned` reborrows through `Deref` by hand (`*owned` is the `str`, `&` borrows it); - `owned.as_str()` or `&owned[..]` for a `String`, `v.as_slice()` for a `Vec`; - a turbofish on the generic, as above. ## Why the rules matter in practice Deref coercion is why a read-only API takes `&str` or `&[T]` and still accepts `&String`, `&Box<String>` or `&mut Vec<T>` without ceremony. It is also why implementing `Deref` is a large commitment for a type's author: every `&YourType` silently becomes a `&Target` at every coercion site in every caller's code, and removing the impl later breaks each of those call sites at once. When a conversion surprises you in review, ask which coercion site produced it and which `Deref` impl it went through; the answer is always a chain of the directions in the table above.

  • Why does passing `&grid` to `fn dump<T: Debug>(value: &T)` fail when `Grid` derefs to a `Debug` type?
    The parameter is generic, so rustc infers `T = Grid` from the argument instead of coercing it, then checks `Grid: Debug` and reports E0277. Coercion needs a known target type, and a type parameter is not one. `dump(&*grid)` or `dump::<Vec<f32>>(&grid)` names the target explicitly.
  • Does deref coercion cost anything at run time?
    The chain length is fixed at compile time, so there is no run-time search, but each step calls the type's `deref` method. For std types that is a field or pointer read the optimiser normally inlines. That is why std says `Deref` should be cheap and should never unexpectedly fail: callers never see the call in their source.

  • Deref coercion can turn a &T into a &mut U when T implements DerefMut.
  • Deref coercion applies one step at most, so &Box<String> cannot become &str.
  • A generic T: Debug parameter accepts any wrapper that derefs to a Debug type.
  • Deref coercion searches for a matching conversion at run time.
  • Declaring the variable mut is enough for &x to coerce to &mut.
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

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