Deref and DerefMut for smart pointer ergonomics

Marcus Chen Jan 2026
1 tab
use std::ops::Deref;

struct MyBox<T>(T);

impl<T> Deref for MyBox<T> {
    type Target = T;
    fn deref(&self) -> &T {
        &self.0
    }
}

fn main() {
    let b = MyBox(String::from("Rust"));
    println!("Length: {}", b.len()); // Deref to &String, then &str
}
1 file · rust Explain with highlit

Implementing Deref lets your type automatically coerce to its target type. For example, Box<T> derefs to T, and String derefs to str. This enables method calls and conversions without explicit unwrapping. I implement Deref for wrapper types and smart pointers. DerefMut is the mutable version. The key is to only use deref coercion for pointer-like types, not as a general inheritance mechanism (Rust doesn't have inheritance). Deref coercion makes smart pointers feel natural: you can call methods on a Box<T> as if it were a T. It's a small feature that improves ergonomics significantly.