]>
Commit | Line | Data |
---|---|---|
8bb4bdeb | 1 | # Coercions |
c1a9b12d | 2 | |
136023e0 XL |
3 | Types can implicitly be coerced to change in certain contexts. |
4 | These changes are generally just *weakening* of types, largely focused around pointers and lifetimes. | |
5 | They mostly exist to make Rust "just work" in more cases, and are largely harmless. | |
c1a9b12d | 6 | |
136023e0 | 7 | For an exhaustive list of all the types of coercions, see the [Coercion types] section on the reference. |
c1a9b12d | 8 | |
136023e0 XL |
9 | Note that we do not perform coercions when matching traits (except for receivers, see the [next page][dot-operator]). |
10 | If there is an `impl` for some type `U` and `T` coerces to `U`, that does not constitute an implementation for `T`. | |
11 | For example, the following will not type check, even though it is OK to coerce `t` to `&T` and there is an `impl` for `&T`: | |
c1a9b12d | 12 | |
532ac7d7 | 13 | ```rust,compile_fail |
c1a9b12d SL |
14 | trait Trait {} |
15 | ||
16 | fn foo<X: Trait>(t: X) {} | |
17 | ||
18 | impl<'a> Trait for &'a i32 {} | |
19 | ||
c1a9b12d SL |
20 | fn main() { |
21 | let t: &mut i32 = &mut 0; | |
22 | foo(t); | |
23 | } | |
24 | ``` | |
25 | ||
136023e0 XL |
26 | which fails like as follows: |
27 | ||
c1a9b12d | 28 | ```text |
0bf4aa26 | 29 | error[E0277]: the trait bound `&mut i32: Trait` is not satisfied |
136023e0 | 30 | --> src/main.rs:9:9 |
0bf4aa26 | 31 | | |
136023e0 XL |
32 | 3 | fn foo<X: Trait>(t: X) {} |
33 | | ----- required by this bound in `foo` | |
34 | ... | |
0bf4aa26 | 35 | 9 | foo(t); |
136023e0 | 36 | | ^ the trait `Trait` is not implemented for `&mut i32` |
0bf4aa26 XL |
37 | | |
38 | = help: the following implementations were found: | |
39 | <&'a i32 as Trait> | |
136023e0 | 40 | = note: `Trait` is implemented for `&i32`, but not for `&mut i32` |
c1a9b12d | 41 | ``` |
136023e0 XL |
42 | |
43 | [Coercion types]: ../reference/type-coercions.html#coercion-types | |
44 | [dot-operator]: ./dot-operator.html |