Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Core Traits

The Deref and DerefMut traits

Reference for the Rust Deref and DerefMut traits: the * operator, deref coercion from &String to &str, building smart pointers, and the Deref polymorphism trap.

Deref customizes what the unary * operator does and, more importantly, enables deref coercion: when a function expects &str and you hold a &String, or expects &[T] and you hold a &Vec<T>, the compiler inserts the deref calls for you. Method calls use the same mechanism to find methods on the pointee, so boxed_string.len() works.

DerefMut is the mutable counterpart. Smart pointers (Box<T>, Rc<T>, Arc<T>, String, Vec<T>, MutexGuard<T>, Ref<T>) all implement Deref.

Rust
let s = String::from("hi");
let r: &str = &s; // &String coerces to &str via Deref

Try it

Rust Deref coercion and a custom smart pointer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust Explicit deref and the * operator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
pub trait Deref {
    type Target: ?Sized;
    fn deref(&self) -> &Self::Target;
}

pub trait DerefMut: Deref {
    fn deref_mut(&mut self) -> &mut Self::Target;
}
Name Description
Target The type you get after dereferencing. It may be unsized (str, [T], dyn Trait).
&self / &mut self The pointer; return a reference to the pointee inside it.

Returns: a reference to Target. The call must be cheap, must not fail and must not do surprising side effects, because the compiler may insert it anywhere.

Usage notes

  • *x means *Deref::deref(&x) in a read context and *DerefMut::deref_mut(&mut x) in a write context. For &T and Box<T> the compiler handles * natively, and moving out with *boxed is only allowed for Box.
  • Deref coercion converts &U to &T when U: Deref<Target = T>, repeatedly if needed, and &mut U to &mut T with DerefMut. It also converts &mut T to &T. It only happens at coercion sites such as function arguments, let with a type annotation and struct fields, not in generic bounds like T: AsRef<str>.
  • Method lookup auto-derefs. rc.len() tries Rc<String>, then String, then str. This is why smart pointers feel transparent.
  • Only for pointer-like types. Using Deref to fake inheritance (impl Deref for Dog { Target = Animal }) is an anti-pattern: it leaks every method, confuses trait resolution and surprises readers. Prefer composition with explicit forwarding or a trait.
  • Fields are not hidden: a wrapper with Deref exposes the target's methods, but your own methods win when names clash, and the target's associated functions (T::new) are not forwarded.
  • Associated functions of the pointer should not be methods. Rc::clone(&a) is written that way so a.clone() keeps meaning "clone the pointee" when it is ambiguous. Follow that style in your smart pointers.
  • Unrelated to Drop. A smart pointer typically implements both: Deref for access and Drop for cleanup.
  • Alternatives: AsRef for explicit, multi-target views; Borrow when lookups must stay consistent.