Types can implicitly be coerced to change in certain contexts. These changes are generally just weakening of types, largely focused around pointers and lifetimes. They mostly exist to make Rust "just work" in more cases, and are largely harmless.
Here's all the kinds of coercion:
Coercion is allowed between the following types:
T_1
`T_1to
` to T_3
`T_3where
` where T_1
`T_1coerces to
T_2and
` and T_2
`T_2coerces to
T_3`&mut T
`&mut Tto
` to &T
`&T`*mut T
`*mut Tto
` to *const T
`*const T`&T
`&Tto
` to *const T
`*const T`&mut T
`&mut Tto
` to *mut T
`*mut T`T
`Tto
` to U
`Uif
` if T
`Timplements
CoerceUnsized`CoerceUnsized<Pointer<U>> for Pointer<T> where T: Unsize<U>
is implemented
for all pointer types (including smart pointers like Box and Rc). Unsize is
only implemented automatically, and enables the following transformations:
[T, ..n]
`[T, ..n]=>
` => [T]
`[T]`T
`T=>
` => Trait
`Traitwhere
` where T: Trait
`T: Trait`Foo<..., T, ...>
=> Foo<..., U, ...>
where:
T: Unsize<U>
Foo
`Foo` is a structFoo
`Foohas type
` has type T
`T`T
`T` is not part of the type of any other fieldsCoercions occur at a coercion site. Any location that is explicitly typed
will cause a coercion to its type. If inference is necessary, the coercion will
not be performed. Exhaustively, the coercion sites for an expression e
`eto type
` to
type U
`U` are:
let x: U = e
takes_a_U(e)
fn foo() -> U { e }
Foo { some_u: e }
let x: [U; 10] = [e, ..]
let x: (U, ..) = (e, ..)
let x: U = { ..; e }
Note that we do not perform coercions when matching traits (except for
receivers, see below). If there is an impl for some type U
`Uand
` and T
`Tcoerces to
U, that does not constitute an implementation for
T. For example, the following will not type check, even though it is OK to coerce
tto
` to &T
`&Tand there is an impl for
&T`:
trait Trait {} fn foo<X: Trait>(t: X) {} impl<'a> Trait for &'a i32 {} fn main() { let t: &mut i32 = &mut 0; foo(t); }
<anon>:10:5: 10:8 error: the trait `Trait` is not implemented for the type `&mut i32` [E0277]
<anon>:10 foo(t);
^~~