Sub topic 6
Deref: treating a smart pointer like a reference
This chapter assumes you know Rust ownership and borrowing, basic generics and traits, and how a reference is dereferenced with *. It covers the Deref trait, which lets a smart pointer behave like a reference.
Why Deref exists
A plain reference &T points at a value, and *r follows the pointer to reach it. A smart pointer such as Box<T> is a struct that owns its data, so the compiler has no built-in way to follow it. The Deref trait supplies that. When a type implements Deref, the * operator works on it.
The trait has one associated type and one method:
Targetis the type you get after dereferencing.deref(&self) -> &Self::Targetreturns a reference to the inner value.
Building MyBox
The best way to see this is to write a minimal Box-like type. MyBox<T> is a tuple struct that holds one value. It does not use the heap, because the goal is to show Deref, not allocation.
use std::ops::Deref;
struct MyBox<T>(T);
impl<T> MyBox<T> {
fn new(x: T) -> MyBox<T> {
MyBox(x)
}
}
impl<T> Deref for MyBox<T> {
type Target = T;
fn deref(&self) -> &T {
&self.0
}
}
fn greet(name: &str) {
println!("Hello, {name}!");
}
fn main() {
let y = MyBox::new(5);
assert_eq!(5, *y);
let name = MyBox::new(String::from("Rust"));
greet(&name);
}Without the Deref impl, *y fails to compile with an error saying MyBox<{integer}> cannot be dereferenced.
What `*y` really does
Writing *y is shorthand. The compiler rewrites it as *(y.deref()). The call to deref returns a plain reference, &i32 here, and the outer * follows that reference to the value.
deref returns a reference, not the value itself. If it returned T, the value would be moved out of the smart pointer, and ownership would transfer on every dereference. Returning &T keeps ownership inside the pointer.
The rewrite also happens only once. Each * calls deref one time and does not recurse.
Using it in a call
In main, greet(&name) passes a &MyBox<String> to a function that expects &str. This compiles because the compiler inserts deref calls until the types match. That behavior is called deref coercion, and the next chapter covers it in detail. For now, note that it only works because MyBox implements Deref.
Common errors
- Forgetting
type Target. The trait requires the associated type, and the code will not compile without it. - Expecting
*yto move the value out. For non-Copytypes,let s = *my_box_of_string;fails with "cannot move out of dereference" forMyBox. Only the built-inBox<T>supports moving out through*. - Assuming
Derefis for any wrapper. The standard library documentation advises implementingDerefonly for smart-pointer-like types. Using it to imitate inheritance can confuse readers.
Exercise
In impl<T> Deref for MyBox<T>, why does deref return &T instead of T?
Show answer
Returning T would move the value out of the smart pointer each time it is dereferenced, taking ownership away from MyBox. Returning &T lends the inner value, so MyBox keeps ownership and *y can be used repeatedly.