What Is the Deref Trait and How Does It Enable Smart Pointer Ergonomics?

The Deref trait allows smart pointers to be treated like regular references by enabling automatic dereferencing for ergonomic syntax.

The Deref trait enables smart pointers to behave like regular references by allowing the compiler to automatically dereference them when accessing fields or calling methods. Implementing Deref on a custom smart pointer type lets you use the * operator or access methods directly on the pointer without explicit dereferencing, creating ergonomic syntax similar to standard references.

use std::ops::Deref;

struct MyBox<T>(T);

impl<T> Deref for MyBox<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

fn main() {
    let x = MyBox(5);
    println!("{}", *x); // Automatically calls deref()
}