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.
fn shout(s: &str) -> String { s.to_uppercase() } let owned = String::from("hi"); shout(&owned); // &String is coerced to &str
Try it
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.
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.
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).
letwith an explicit type,staticandconstinitializers.- Struct, enum-variant and array/tuple element expressions where the field type is known.
- The final expression of a block and
returnvalues, 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&Pathrather than&String,&Vec<T>and&PathBuf; callers with either form can pass&valueand coercion does the rest. - No coercion into generics:
fn f<T: AsRef<str>>(t: T)receives exactly the type you passed. That is whyAsRefexists. - Mutable to shared is allowed; the reverse is not. A
&Tcan never become&mut T. - Reborrows: passing a
&mut Tvariable to a function that takes&mut Timplicitly 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
Dereffor your own types enables these coercions, but use it only for smart-pointer-like wrappers. UsingDereffor 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.
asis separate:ascasts for numbers and raw pointers are explicit conversions, not coercions. See conversions.