skip to content

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%

answer

  1. Deref is not inheritance
  2. method lookup falls through to the target
  3. the wrapper's own traits stay missing
  4. DerefMut exposes every &mut method

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.

solid answer

~40 s

`Deref` only tells rustc how to get a `&Vec<f32>` from a `&Grid`; it creates no subtype. Method lookup tries `Grid` first and then the deref target, so with no `Clone` on `Grid`, `grid.clone()` silently resolves to `Vec::clone` and returns a `Vec<f32>`, and `grid.len()` reports 6 cells for a 2-by-3 grid. With `DerefMut`, every `&mut self` method of `Vec`, such as `push`, `clear` and `truncate`, is callable on the grid, so any caller can break the `cells.len() == rows * cols` invariant the constructor set up. Traits do not transfer either: `Vec<f32>: Debug` does not make `Grid: Debug`, so a generic `fn dump<T: Debug>` rejects `&grid` with E0277. The repair is to drop the `Deref` impls, implement the traits `Grid` really has, and expose only the operations it can guarantee.

code

rust · 23 lines
rust
use std::ops::{Deref, DerefMut};

struct Grid { cols: usize, cells: Vec<f32> }

impl Deref for Grid {
    type Target = Vec<f32>;
    fn deref(&self) -> &Vec<f32> { &self.cells }
}
impl DerefMut for Grid {
    fn deref_mut(&mut self) -> &mut Vec<f32> { &mut self.cells }
}

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

fn main() {
    let mut grid = Grid { cols: 3, cells: vec![1.0; 6] };
    println!("mean = {}", mean(&grid));      // &Grid -> &Vec<f32> -> &[f32]
    println!("len = {}", grid.len());        // Vec::len: 6 cells, not 2 rows
    let copy = grid.clone();                 // Grid is not Clone: this is Vec::clone
    let _: &Vec<f32> = &copy;
    grid.push(9.0);                          // DerefMut: 7 cells, invariant rows * cols broken
    println!("cells = {}, cols = {}", grid.len(), grid.cols);
}

go deeper

for a junior

Recall that Deref lets a wrapper borrow as its inner type, and that this is not inheritance: the wrapper gets no traits from it.

for a middle

Explain why method calls fall through to the target, which type clone() returns there, and why a generic T: Debug bound rejects the wrapper.

for a senior

Spot the invariant break DerefMut enables, the silent shadowing when inherent methods are added, and replace Deref with explicit accessors and real trait impls.

for a principal

Frame Deref as a public-API commitment: every target method becomes the wrapper's surface, so a review rule should demand justification before a newtype implements it.

## What `Deref` actually grants `std::ops::Deref` has one method, `fn deref(&self) -> &Self::Target`, and `DerefMut` adds `fn deref_mut(&mut self) -> &mut Self::Target`. Implementing them for a wrapper gives the compiler permission to insert those calls silently. The std documentation lists the consequences for `T: Deref<Target = U>`: - `*v` means `*Deref::deref(&v)`; - a `&T` coerces to `&U` at coercion sites such as function arguments; - `T` behaves as if it had every `&self` method of `U`, and with `DerefMut`, every `&mut self` method too. None of these makes `Grid` a kind of `Vec`. There is no subtyping between distinct struct types in Rust, no overriding, and no way for `Vec`'s methods to know a `Grid` is calling them. The habit of reaching for `Deref` to "inherit" a field's methods is called the **Deref-as-inheritance anti-pattern**. ## Four symptoms from one wrapper The example in this question compiles cleanly on rustc 1.99.1, which is the problem: each surprise is legal code. 1. **`grid.clone()` returns a `Vec<f32>`.** Method lookup tries receiver types in order: `Grid`, `&Grid`, `&mut Grid`, then the deref target `Vec<f32>` and its references. `Grid` has no `Clone`, so the first match is `Vec::clone`. The caller expected a second grid and got a bare vector with no column count. (Had the receiver been a `&Grid`, lookup would clone the reference instead, which rustc flags with the `noop_method_call` lint.) 2. **`grid.len()` answers the wrong question.** It is `Vec::len`, the cell count. Worse, if someone later adds an inherent `fn len(&self) -> usize` on `Grid` returning rows, every existing call silently switches to it, because inherent methods on `Grid` are found before the target's. No compile error flags the change in meaning. 3. **`grid.push(9.0)` breaks the invariant.** Through `DerefMut`, the grid now holds 7 cells with 3 columns. Any later cell lookup, row slice or iteration by rows would be wrong, and the bug surfaces far from the `push`. 4. **Generic code does not see through the wrapper.** `fn dump<T: Debug>(value: &T)` called with `&grid` fails with **E0277**, "`Grid` doesn't implement `Debug`", even though `Vec<f32>` is `Debug`. Trait bounds are checked on the type you pass, and no impl is inherited. | Expectation carried over from inheritance | What `Deref` really does | |---|---| | The wrapper is usable wherever the inner type is | Only `&Grid` to `&Vec<f32>` at coercion sites; generic bounds see `Grid` | | Inherited methods return the wrapper | They return whatever `Vec`'s method returns, often a `Vec` | | The wrapper can override a method | An inherent method shadows the target's, with no signal at call sites | | The wrapper's invariants are protected | `DerefMut` hands out `&mut Vec<f32>` to anyone | ## Why read-only `Deref` is only half a fix Dropping `DerefMut` and keeping `Deref` stops `push` (rustc then reports **E0596**, "cannot borrow data in dereference of `Grid` as mutable", and says `DerefMut` is required). Symptoms 1, 2 and 4 remain, and the grid's public API still includes every `&self` method of `Vec<f32>`, now a promise to callers. std's `Deref` docs warn that deref traits are "a much larger part of a type's public API than any other trait", and advise against implementing them when "the type has methods that are likely to collide with methods on the target type", which is precisely `len` here. ## The repair - Remove both `Deref` impls. - Derive or implement what the grid really is: `#[derive(Debug, Clone, PartialEq)]` gives `grid.clone()` the type `Grid`. - Expose explicit, invariant-preserving accessors: `rows()`, `cols()`, `row(r) -> &[f32]`, `as_slice() -> &[f32]` for read access, and `Index<(usize, usize)>`/`IndexMut` for cell access. - Where callers need to pass the cells to slice-taking functions, `grid.as_slice()` is one explicit call instead of a silent coercion. ## How to spot it in review - An `impl Deref` whose target is a collection or a domain type rather than the pointee of a pointer-like wrapper. - Any `DerefMut` on a type whose constructor validates or normalises its contents. - Call sites that use the target's methods on the wrapper, such as `grid.iter()` or `grid.len()`, where a reader must know the `Deref` impl exists to understand what runs. The test of whether a wrapper may implement `Deref` is whether it is a pointer-like or storage-like layer that adds nothing to the value. A `Grid` adds a shape invariant, so it fails that test.

  • If the Rust `Grid` keeps only `Deref` and drops `DerefMut`, which problems remain?
    `push` and `clear` stop compiling (E0596, with help saying `DerefMut` is required), because a `&Vec<f32>` cannot change the vector's length, so the shape invariant is safe. But `clone()` still returns a `Vec<f32>`, `len()` still counts cells, generic bounds still reject `&grid`, and every `&self` method of `Vec` is now part of the grid's public API.
  • Why can adding a method to a Rust wrapper that implements `Deref` change existing behaviour without a compile error?
    Method lookup tries the wrapper's own methods before the deref target's. Adding an inherent `len` on `Grid` makes every existing `grid.len()` call resolve to it instead of `Vec::len`; the code still type-checks, so the change in meaning goes unflagged. std cites name collisions as a reason not to implement `Deref`.

  • Implementing Deref makes the newtype inherit the inner type's trait impls.
  • grid.clone() on a Deref wrapper always returns another Grid.
  • DerefMut is harmless because the wrapper's constructor already validated the data.
  • Inherited methods through Deref return the wrapper type, like overridden methods.
  • Adding a same-named inherent method causes a compile error at existing call sites.