Sub topic 6
Deref: treating a smart pointer like a reference
This chapter assumes you know Rust's ownership and borrowing rules, how references work, and how to read a basic trait implementation with generics. It builds on the previous chapter's idea that a smart pointer is a struct that owns data and adds behavior. Here you will see how the Deref trait lets such a struct respond to the * operator and to method calls the way a reference does.
The dereference operator
A reference points at a value somewhere else. The * operator follows that pointer to the value. Box<T> supports the same operator.
fn main() {
let x = 5;
let r = &x;
let b = Box::new(x);
assert_eq!(5, x);
assert_eq!(5, *r);
assert_eq!(5, *b);
println!("all three comparisons hold");
}assert_eq!(5, r) would not compile, because an integer and a reference to an integer are different types. You must write *r. A Box<i32> behaves the same way, so *b gives the i32 inside.
A struct you define yourself does not get this behavior. If you write struct MyBox<T>(T); and then use *y on a MyBox<i32>, the compiler reports that the type cannot be dereferenced. Dereferencing is not built into every type. It comes from a trait.
Implementing Deref
The Deref trait, from std::ops, has one associated type and one method:
type Targetnames the type you get after dereferencing.fn deref(&self) -> &Self::Targetreturns a reference to that inner value.
Here is a minimal MyBox that supports *. It stores its value inline, with no heap allocation, because the goal is only to show the trait.
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 main() {
let y = MyBox::new(5);
assert_eq!(5, *y);
println!("*y = {}", *y);
}The program prints *y = 5.
What the compiler does with `*y`
When the compiler sees *y and y is not a plain reference, it rewrites the expression:
*y becomes *(y.deref())deref returns &T, a reference. The outer * is then an ordinary dereference of that reference. The method returns a reference instead of the value itself for ownership reasons. If deref returned T by value, using *y would move the value out of the smart pointer and leave it unusable. Returning &T lets the pointer keep ownership.
The rewrite happens once per *. It does not loop until it reaches a plain value.
Method calls dereference automatically
You rarely write * by hand when calling methods. For value.method(), the compiler tries the receiver type, then & and &mut versions of it, and then dereferences the receiver using Deref and repeats. This is called auto-dereferencing on method calls.
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 name = MyBox(String::from("Rust"));
println!("{}", name.len());
println!("{}", name.to_uppercase());
println!("{}", (*name).len());
println!("{}", name.deref().len());
}The output is 4, RUST, 4, 4. MyBox has no len method. The compiler finds no match on MyBox<String>, calls deref to get a &String, finds no match there either, and derefs again through String to str, where len exists. All four lines compute the same thing, and the first is the one you would normally write.
Function arguments get a related conversion, called deref coercion. The next chapter covers it.
Deref and DerefMut
Deref handles immutable access. For mutable access you also implement DerefMut, which requires Deref and adds fn deref_mut(&mut self) -> &mut Self::Target.
use std::ops::{Deref, DerefMut};
struct MyBox<T>(T);
impl<T> Deref for MyBox<T> {
type Target = T;
fn deref(&self) -> &T {
&self.0
}
}
impl<T> DerefMut for MyBox<T> {
fn deref_mut(&mut self) -> &mut T {
&mut self.0
}
}
fn main() {
let mut y = MyBox(5);
*y += 1;
assert_eq!(*y, 6);
let mut v = MyBox(vec![1, 2]);
v.push(3);
println!("{:?}", *v);
}The program prints [1, 2, 3]. The compiler picks the trait from the context of the use:
| Context | Trait used |
|---|---|
| `*y` read in an immutable position | `Deref` |
| `*y` assigned to or borrowed mutably, and `y` is `mut` | `DerefMut` |
| Method taking `&self` on the target | `Deref` |
| Method taking `&mut self` on the target, as in `push` | `DerefMut` |
Without DerefMut, *y += 1 and v.push(3) fail to compile even though Deref is implemented. The binding must also be declared mut.
Common errors
Moving out through a dereference. With the MyBox<String> above, let s: String = *name; fails with error E0507, "cannot move out of dereference". deref only hands out a reference, so *name is a place you can borrow or copy from, not something you can take ownership of. Clone it with (*name).clone() or borrow it with &*name. Box<T> is the exception. The compiler special-cases it, so *boxed can move the value out.
Missing Target. impl Deref requires type Target. Leaving it out is a compile error. The Target you pick also fixes what *y means, so deref must return &Self::Target, not &Self.
One Deref target per type. Target is an associated type, not a generic parameter. A type has exactly one target, which is why method lookup has a single, predictable chain to follow.
Expecting Deref to compare or convert. Deref does not make MyBox<i32> equal to i32. assert_eq!(5, y) fails because the types differ. You must write *y.
Summary of the working model
*yon a non-reference type means*(y.deref()).derefreturns a reference so the pointer keeps ownership of its data.- Method calls apply
Derefrepeatedly until a matching method is found. DerefMutis a separate trait for mutable access, and you needmutbindings to use it.Box<T>,Rc<T>,String, andVec<T>all implementDeref, which is whyRc<String>lets you callstrmethods directly.
Exercise
Given the MyBox<T> type from this chapter with only Deref implemented, let mut y = MyBox::new(10); *y += 1; fails to compile. Which trait is missing, and what method must it supply?
Show answer
DerefMut is missing. It requires fn deref_mut(&mut self) -> &mut T, which returns &mut self.0. With only Deref, the compiler can produce a shared &T but not the &mut T that += needs. The binding y is already declared mut, so that is not the problem.
Exercise
Why does Deref::deref return &Self::Target rather than Self::Target?
Show answer
Returning the value by value would move it out of the smart pointer, so *y would consume y and the pointer could not be used afterward. Returning a reference lets the pointer keep ownership. The compiler then applies a plain * to that reference, so *y is *(y.deref()).