Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Concepts

Deref and unsized coercions in Rust

Reference for Rust coercions: deref coercion (&String to &str), unsized coercion (array to slice, Box to dyn Trait), reborrows, coercion sites and what never coerces.

Rust is strict about types, but it makes a small set of coercions for you: implicit conversions that the compiler inserts at certain places because they are always safe and cheap. The two you meet daily are deref coercion, which turns &String into &str (and &Vec<T> into &[T]), and unsized coercion, which turns &[T; N] into &[T] or Box<T> into Box<dyn Trait>.

Coercions only happen at coercion sites, such as function arguments, let statements with an explicit type, struct fields and return values. They never change the value: they only change the type of the reference or pointer.

Rust
fn shout(s: &str) -> String { s.to_uppercase() }

let owned = String::from("hi");
shout(&owned);   // &String is coerced to &str

Try it

Rust Deref coercion in function calls

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust Unsizing to a trait object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust Where coercion does not happen

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The coercions

From To Kind
&mut T &T weakening
&T or &mut T &U when T: Deref<Target = U> deref coercion
&mut T &mut U when T: DerefMut<Target = U> deref coercion
&[T; N] &[T] unsized coercion
Box<T>, Rc<T>, Arc<T>, &T the same pointer to dyn Trait when T: Trait unsized coercion
Box<[T; N]> Box<[T]> unsized coercion
! (never) any type diverging expression
non-capturing closure fn pointer closure coercion
fn item fn pointer function coercion

Deref coercion is applied repeatedly: &Box<String> becomes &String and then &str. The compiler keeps calling deref until the types match or no more derefs exist.

Coercion sites

  • Arguments of function and method calls (the expected parameter type is known).
  • let with an explicit type, static and const initializers.
  • Struct, enum-variant and array/tuple element expressions where the field type is known.
  • The final expression of a block and return values, when the return type is declared.

Method calls use a related but separate mechanism, auto-deref on the receiver: owned.len() finds str::len through String: Deref<Target = str> without any coercion site.

Usage notes

  • Write parameters as &str, &[T] and &Path rather than &String, &Vec<T> and &PathBuf; callers with either form can pass &value and coercion does the rest.
  • No coercion into generics: fn f<T: AsRef<str>>(t: T) receives exactly the type you passed. That is why AsRef exists.
  • Mutable to shared is allowed; the reverse is not. A &T can never become &mut T.
  • Reborrows: passing a &mut T variable to a function that takes &mut T implicitly reborrows (&mut *r) instead of moving it, so you can use it afterwards. Inside generic code the move happens, because no coercion site applies.
  • Implementing Deref for your own types enables these coercions, but use it only for smart-pointer-like wrappers. Using Deref for inheritance-style method forwarding is considered an anti-pattern.
  • Surprising ambiguity: a type can both have its own method and deref to something with the same name; the outer type's method wins.
  • as is separate: as casts for numbers and raw pointers are explicit conversions, not coercions. See conversions.