In this lesson, you will learn how to make your custom smart pointers feel like native, built-in types by automatically "collapsing" layers of indirection.
The Problem: Manual Dereferencing
When you wrap a value in a custom smart pointer (a struct that manages its own memory), accessing the inner data usually requires manual effort. If you have a MyBox<T>, you might be forced to type (*my_box).do_something() every time you want to use the inner value. This is noisy and makes your custom types feel like second-class citizens compared to the standard library’s Box<T> or simple references.
The Solution: Deref Coercion
Rust provides a mechanism called Deref Coercion. If your type implements the Deref trait from the standard library, Rust will automatically "unwrap" your smart pointer whenever you pass it to a function or method that expects the inner type.
Imagine you have a custom pointer:
use std::ops::Deref;
struct MyBox<T>(T);
impl<T> Deref for MyBox<T> {
type Target = T;
fn deref(&self) -> &T {
&self.0
}
}
fn say_hello(name: &str) {
println!("Hello, {}!", name);
}
fn main() {
let boxed_name = MyBox(String::from("Rustacean"));
// We pass MyBox, but say_hello expects a &str.
// Rust automatically calls deref() to bridge the gap!
say_hello(&boxed_name);
}
Why This Matters
Without this feature, you would have to manually add dereference operators (*) or call .deref() everywhere in your codebase. By implementing Deref, you are creating an ergonomic abstraction: your custom struct behaves exactly like the data it wraps.
When the Rust compiler sees a type T that implements Deref<Target = U>, and you try to use it where a &U is expected, it silently inserts the necessary deref calls for you. This allows you to build complex memory management tools—like reference counters or unique pointers—that users can interact with as if they were handling raw values.
Key Takeaway: Deref coercion allows custom types to behave like the types they point to, removing the "ceremony" of manual dereferencing and enabling seamless ergonomic usage.