Sub topic 7
Deref coercion in function calls
This chapter assumes you know the Deref trait from the previous chapter, the difference between &T and &mut T, and how to write a function that takes a reference parameter. It covers what the compiler does when you pass a smart pointer reference to a function that expects a different reference type.
The problem coercion solves
Here is the MyBox<T> type from the last chapter, with a function that takes a string slice.
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 call greet(&name) passes a &MyBox<String> to a parameter of type &str. These are different types, yet the program compiles and prints Hello, Rust!.
The compiler converts the argument for you. This is deref coercion. Without it, you would have to write the conversion by hand:
greet(&(*name)[..]);Here *name gives the String, [..] slices it into a str, and & borrows it. Deref coercion removes that noise.
The rule
Deref coercion converts a reference to a type that implements Deref into a reference to the type that Deref::Target names. The compiler calls deref as many times as it needs until the types match.
For greet(&name), it works in two steps:
&MyBox<String>becomes&String, becauseMyBox<String>: Deref<Target = String>.&Stringbecomes&str, becauseString: Deref<Target = str>.
The compiler resolves all of this at compile time. Coercion adds no runtime cost compared with writing the deref calls yourself.
Coercion works with standard library types
Every standard smart pointer implements Deref, so the same mechanism applies to them. A function that takes a slice accepts a reference to a Vec, a Box<Vec>, or an Rc<Vec>.
use std::rc::Rc;
fn total(xs: &[i32]) -> i32 {
xs.iter().sum()
}
fn main() {
let v = vec![1, 2, 3];
let boxed = Box::new(vec![4, 5]);
let shared = Rc::new(vec![6]);
println!("{}", total(&v));
println!("{}", total(&boxed));
println!("{}", total(&shared));
}This prints 6, 9, and 6. The call total(&boxed) follows &Box<Vec<i32>> to &Vec<i32> to &[i32].
This is why idiomatic Rust APIs take &str instead of &String, and &[T] instead of &Vec<T>. The slice parameter accepts more argument types and costs the caller nothing.
Mutability rules
Coercion respects the borrowing rules. It will not turn a shared reference into a mutable one. Three conversions are allowed:
| From | To | Requires |
|---|---|---|
| `&T` | `&U` | `T: Deref<Target = U>` |
| `&mut T` | `&mut U` | `T: DerefMut<Target = U>` |
| `&mut T` | `&U` | `T: Deref<Target = U>` |
The third row works because a mutable reference is the only active reference to the data. Giving up the right to mutate is always safe.
The reverse, &T to &mut U, is never allowed. If it were, a shared reference, which the compiler assumes has many copies, could be used to mutate data. The borrowing rules forbid that.
The second row needs DerefMut, a separate trait from Deref. Box<T> implements it, so this works:
fn shout(s: &mut String) {
s.push('!');
}
fn main() {
let mut b = Box::new(String::from("hi"));
shout(&mut b);
println!("{} {}", b, b.len());
}The output is hi! 3. The argument &mut Box<String> becomes &mut String through DerefMut. The binding b must be declared mut, as it would be for any mutable borrow.
The expression b.len() shows a related feature. Method calls use automatic dereferencing. The compiler tries the receiver type and then each type reachable through Deref, until it finds a method with the given name. Coercion and auto-deref are separate mechanisms, but both rely on Deref.
Where coercion happens
Deref coercion applies at coercion sites, which are places where the compiler knows the target type. The most common are:
- Arguments to function and method calls.
- A
letstatement with a type annotation, such aslet s: &str = &name;. - Struct field initializers, where the field type is declared.
- Return values, when the function signature declares the return type.
It does not apply where the compiler has to infer the type. That leads to the most common surprises.
Common errors
Passing a value instead of a reference
Coercion converts references only. Both of these lines fail to compile with a type mismatch:
greet(name); // expected `&str`, found `MyBox<String>`
greet(*name); // expected `&str`, found `String`Write greet(&name). The leading & creates the reference that coercion starts from.
Generic parameters block coercion
Suppose a function is generic over its parameter, like fn show<T: std::fmt::Display>(t: T). The compiler infers T from the argument, so no coercion target exists. Calling show(&name) makes T = &MyBox<String>. That type is not Display, because MyBox has no Display implementation. The call fails to compile.
The fix is to name the target type yourself. Write show(&*name) or show(name.as_str()). You can also change the parameter to &str.
The same limit applies to trait bounds in general. Coercion adjusts an argument to a concrete expected type. It does not search for a type that satisfies a bound.
Coercion does not change ownership
Coercion only produces a new reference. After greet(&name), you still own name, and MyBox<String> is untouched. No clone happens.
Overusing `Deref` for inheritance
Deref coercion can make a wrapper type look like the type inside it. This is convenient for smart pointers. Using Deref on an ordinary wrapper struct to imitate inheritance is considered an anti-pattern. It makes method resolution hard to predict and exposes every method of the inner type. Implement Deref only for types that really behave like pointers.
Summary of how the compiler decides
- It looks at the argument's type and the parameter's type at a coercion site.
- If they already match, it does nothing.
- If the argument is a reference to a type that implements
Deref(orDerefMutfor&mut), it callsderefrepeatedly and checks the type after each step. - If a step produces the parameter type, it inserts the calls. Otherwise it reports a type mismatch.
Exercise
Given let s = Rc::new(String::from("hi")); and fn len(s: &str) -> usize { s.len() }, which of these compile: len(s), len(&s), len(&*s)? Explain each.
Show answer
len(&s) compiles: &Rc<String> coerces to &String and then to &str. len(&*s) compiles too: *s is a String (through Rc's Deref), and &String coerces to &str. len(s) does not compile: it passes an Rc<String> by value, and coercion applies only to references, so the compiler reports a mismatch between &str and Rc<String>.
Exercise
Why does fn shout(s: &mut String) accept &mut b when b is a Box<String>, but would reject &b?
Show answer
&mut Box<String> coerces to &mut String because Box<String> implements DerefMut<Target = String>. A shared reference &Box<String> can become &String but never &mut String, because coercion cannot turn a shared reference into a mutable one.