skip to content

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%

answer

  1. pointer-like, not domain types
  2. cheap, infallible, unsurprising
  3. public API you cannot take back
  4. accessors and explicit trait impls

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.

solid answer

~50 s

std's own guidance is the baseline: implement the deref traits when the type "transparently behaves like a value of the target type", the deref is cheap, and users will not be surprised; avoid them when the deref could fail, when method names are likely to collide, or when committing to deref coercion as public API is not desirable. The Rust API Guidelines compress this to "Only smart pointers implement `Deref` and `DerefMut`" (C-DEREF). A rule a team can enforce: no `Deref` on domain newtypes such as a `Grid` or a validated ID; `DerefMut` never on a type whose constructor validates; any exception needs a written reason in review. The replacements are explicit accessors (`as_slice`, `into_inner`), `AsRef` where generic callers need a view, and implementing the specific traits the type supports, which costs a few lines but keeps the API deliberate.

code

rust · 30 lines
rust
#[derive(Debug, Clone, PartialEq)]
pub struct Grid {
    rows: usize,
    cols: usize,
    cells: Vec<f32>,
}

impl Grid {
    pub fn new(rows: usize, cols: usize) -> Grid {
        Grid { rows, cols, cells: vec![0.0; rows * cols] }
    }
    pub fn rows(&self) -> usize { self.rows }
    pub fn as_slice(&self) -> &[f32] { &self.cells }
    pub fn row(&self, r: usize) -> &[f32] { &self.cells[r * self.cols..(r + 1) * self.cols] }
    pub fn into_inner(self) -> Vec<f32> { self.cells }
}

impl AsRef<[f32]> for Grid {
    fn as_ref(&self) -> &[f32] { &self.cells }
}

fn mean(values: &[f32]) -> f32 { values.iter().sum::<f32>() / values.len() as f32 }

fn main() {
    let grid = Grid::new(2, 3);
    println!("{} rows, mean {}", grid.rows(), mean(grid.as_slice()));
    println!("row 1 = {:?}", grid.row(1));
    let cells = grid.into_inner();
    println!("{} cells", cells.len());
}

go deeper

for a junior

Recall the API Guidelines' line that only smart pointers implement Deref and DerefMut, and that Deref on a newtype is a known anti-pattern.

for a middle

Explain std's three reasons to implement Deref and three reasons not to, and name the explicit alternatives: accessors, into_inner and AsRef.

for a senior

Review a newtype's Deref impl against its invariants, catch DerefMut on validated types, and replace it with forwarded methods and real trait impls.

for a principal

Set the team default to no Deref on newtypes, define the narrow exceptions and their review bar, and weigh boilerplate against an API surface you cannot later retract.

## Why this is a lead's decision Implementing `Deref` on a newtype is a one-line change with a long tail. Once `impl Deref<Target = Vec<f32>> for Grid` ships, every `&self` method of `Vec<f32>` is callable on a `Grid` in every downstream crate, every `&Grid` coerces to `&Vec<f32>` and `&[f32]` at coercion sites, and the inner representation is fixed as public API. Removing the impl later breaks those callers. std's documentation says it plainly: deref traits are "a much larger part of a type's public API than any other trait as it is implicitly called by the compiler". That makes it a team convention to set once, not a choice for each reviewer to re-argue. ## What the standard library says The `Deref` docs give both lists. Implement the deref traits if: 1. a value of the type transparently behaves like a value of the target type; 2. the implementation of the deref function is cheap; and 3. users of the type will not be surprised by any deref coercion behaviour. Do not implement them if: 1. the deref implementations could fail unexpectedly; 2. the type has methods likely to collide with methods on the target type; or 3. committing to deref coercion as part of the public API is not desirable. The docs also note that a generic wrapper such as `Box<T>` "should be careful to provide few or no methods", since any method could collide with one on the unknown target. The API Guidelines' checklist entry C-DEREF states the conclusion: "Only smart pointers implement `Deref` and `DerefMut`", listing `Box`, `String` (a smart pointer to `str`), `Rc`, `Arc` and `Cow` as examples. These are "should" statements: the compiler enforces none of them, so a team rule is how they get applied. ## A rule a team can enforce - **Default: no `Deref` on newtypes.** A domain newtype exists to add meaning or an invariant, which is exactly what deref coercion bypasses. - **`Deref` allowed** for pointer-like or storage-like wrappers that add no invariant and whose target API is a commitment the team accepts, such as a wrapper that changes where or how a value is stored. - **`DerefMut` allowed only** when no mutation of the target could violate the wrapper's guarantees. A `Grid` that must keep `rows * cols` cells fails this test; read-only `Deref` alone would not let callers resize it, but it still exports all of `Vec`'s read API. - **Every exception is reviewed** with a one-line justification beside the impl, naming which of std's three conditions it meets. - **Never fallible.** A `deref` that can panic outside programmer error is rejected, because callers never see the call. ## What to use instead | Need | Replacement | Cost | |---|---|---| | Read access to the inner data | `as_slice(&self) -> &[f32]` or `inner(&self) -> &T` | one method; the call is visible | | Give the inner value back | `into_inner(self) -> T` | one method | | Generic callers want a view | `impl AsRef<[f32]> for Grid` | explicit at bound sites, no silent method surface | | The type should be `Debug`, `Clone`, `Index` | derive or implement those traits | keeps the wrapper's own semantics | | Callers need a few inner methods | forward them by hand: `fn len(&self) -> usize { self.cells.len() }` | some boilerplate, but each method is a decision | The forwarding cost is the honest trade: a few lines per method in exchange for an API whose every entry was chosen. Teams that find the boilerplate heavy usually discover they wanted only three or four methods, not the target's full surface. ## Edge cases worth arguing about - **A string-like identifier with no validation.** If a newtype over `String` truly adds nothing, `Deref<Target = str>` is defensible; once it validates its contents, `DerefMut` is out and `Deref` is a judgment call against the collision risk. - **Interior mutability in the target.** Read-only `Deref` does not freeze a target whose `&self` methods mutate through a `Cell` or `RefCell`; check the target's API, not just the trait name. - **Wrappers in a published library.** Adding `Deref` later is easy; removing it is a breaking change, so libraries should start without it. - **Wrappers whose job is ownership or storage** are the smart pointers that std's own `Deref` impls cover, a separate topic in the smart-pointer lessons.

  • Is read-only `Deref` an acceptable compromise for a Rust wrapper that carries an invariant?
    Sometimes. With no `DerefMut`, callers cannot reach the target's `&mut self` methods, and a `&Vec<f32>` cannot change the vector's length, so a `Grid`'s cell count is safe. But the whole `&self` API of the target becomes the wrapper's public API, names can collide, and `clone()` may still resolve to the target. Accept it only when that surface is one you would have chosen anyway.
  • How do you justify the boilerplate of forwarding methods instead of implementing `Deref`?
    Each forwarded method is a deliberate API entry: it returns the wrapper's own types, keeps invariants checkable, and can change its implementation without breaking callers. `Deref` exports the target's entire surface at once and is a breaking change to remove. In practice most wrappers need only a handful of forwarded methods.

  • Deref is the idiomatic way to give a newtype its inner type's methods.
  • rustc rejects a Deref impl that does not wrap a pointer type.
  • DerefMut is fine on a validated type because constructors already checked it.
  • Removing a Deref impl later is a compatible, non-breaking change.
  • Forwarding methods by hand is always worse than one Deref impl.