Sub topic 7
Deref coercion in function calls
This chapter assumes you know references and function signatures, and that you have seen the Deref trait from the previous chapter. It covers how the compiler uses Deref to convert reference types automatically at call sites.
What deref coercion does
Deref coercion converts a reference to a type that implements Deref into a reference to the type that Deref targets. The compiler applies deref as many times as needed to make the types match. This happens at compile time, so it costs nothing at runtime.
The example below passes a &MyBox<String> to a function that expects &str.
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);
}The program prints Hello, Rust!. The argument &name has type &MyBox<String>, but greet wants &str. The compiler finds a chain of conversions:
&MyBox<String>becomes&String, usingMyBox'sDerefimplementation.&Stringbecomes&str, using the standard library'sDerefimplementation forString.
Without coercion
Without deref coercion, you would write the conversions by hand:
greet(&(*name)[..]);Here *name gives the String, and [..] takes a string slice of the whole value. The & makes it a reference. This is harder to read, and it is the reason coercion exists.
Which coercions are allowed
Coercion works from one reference kind to another in these cases:
| From | To | Requirement |
|---|---|---|
| `&T` | `&U` | `T: Deref<Target = U>` |
| `&mut T` | `&mut U` | `T: DerefMut<Target = U>` |
| `&mut T` | `&U` | `T: Deref<Target = U>` |
The last row works because a mutable reference can always be used as a shared one. The reverse does not work. Borrowing rules allow only one mutable reference to a value, and a shared reference gives no guarantee that it is the only one. Converting &T to &mut U is therefore rejected.
Common errors
- Coercion only applies to references. Passing
nameby value, without&, gives a type mismatch. - It applies where the compiler knows the target type. Function arguments and method calls qualify. A generic parameter
Taccepts anything, so no coercion happens there and the argument keeps its own type. &mutneedsDerefMut. If your type implements onlyDeref, you cannot coerce it to&mut U.
Exercise
A function has the signature fn shout(text: &str). You hold let s = Box::new(String::from("hi"));. Does shout(&s) compile? Which conversions does the compiler apply?
Show answer
Yes, it compiles. &s has type &Box<String>. The compiler derefs it to &String using Box's Deref implementation, then to &str using String's Deref implementation.