liveBook · Manning

Deref coercion

As explained in Idiomatic Rust

Deref coercion is Rust's automatic conversion of a reference to a wrapper value into a reference to its dereference target when resolving method calls and compatible operations.

Deref coercion lets a wrapper behave like its dereference target for method calls. Implement `Deref` with a `Target` type and a `deref` method returning a reference to the wrapped value; the compiler can then resolve methods on that target. section 7.2.2 section 10.6

impl<T> Deref for WrappedVec<T> {
    type Target = Vec<T>;               #1
    fn deref(&self) -> &Self::Target {
        &self.0                         #2
    }
}

This implementation makes `Vec` methods such as `iter()` available through `WrappedVec`. section 7.2.2

Keep the method-call convenience distinct from these limitations:

  • Methods requiring `&mut self` need `DerefMut` on the wrapper. section 7.2.2
  • Deref does not expose methods that consume the wrapped value, such as `into_iter()`; provide an appropriate wrapper method for those operations. section 7.2.2

Convenience is not polymorphism

A `Person` wrapping strings can use `ferris.len()` through Deref coercion, but the call obscures that it measures the first name. A clearly named method is easier to understand. Avoid using Deref to imitate polymorphism; use traits and generics, trait objects, or an explicit method that returns the inner value when appropriate. section 10.6 section 10.6

How Idiomatic Rust covers it

How deep it goes
Explains the Deref implementation and method access, then notes mutable and by-value limits and warns against emulating polymorphism.
Examples
Uses a WrappedVec exposing Vec methods and a Person exposing String methods, then contrasts Deref with trait-based polymorphism.
What you can do after
Apply Deref coercion to expose wrapped-type methods while recognizing when explicit methods or trait-based alternatives are clearer.
How it connects
Connects Deref coercion to DerefMut, smart pointers, method calls, traits, generics, and trait objects.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Idiomatic Rust. The section links point to the parts of the book it draws on.