]> git.proxmox.com Git - rustc.git/blame - src/doc/nomicon/src/coercions.md
New upstream version 1.55.0+dfsg1
[rustc.git] / src / doc / nomicon / src / coercions.md
CommitLineData
8bb4bdeb 1# Coercions
c1a9b12d 2
136023e0
XL
3Types can implicitly be coerced to change in certain contexts.
4These changes are generally just *weakening* of types, largely focused around pointers and lifetimes.
5They mostly exist to make Rust "just work" in more cases, and are largely harmless.
c1a9b12d 6
136023e0 7For an exhaustive list of all the types of coercions, see the [Coercion types] section on the reference.
c1a9b12d 8
136023e0
XL
9Note that we do not perform coercions when matching traits (except for receivers, see the [next page][dot-operator]).
10If there is an `impl` for some type `U` and `T` coerces to `U`, that does not constitute an implementation for `T`.
11For 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
14trait Trait {}
15
16fn foo<X: Trait>(t: X) {}
17
18impl<'a> Trait for &'a i32 {}
19
c1a9b12d
SL
20fn main() {
21 let t: &mut i32 = &mut 0;
22 foo(t);
23}
24```
25
136023e0
XL
26which fails like as follows:
27
c1a9b12d 28```text
0bf4aa26 29error[E0277]: the trait bound `&mut i32: Trait` is not satisfied
136023e0 30 --> src/main.rs:9:9
0bf4aa26 31 |
136023e0
XL
323 | fn foo<X: Trait>(t: X) {}
33 | ----- required by this bound in `foo`
34...
0bf4aa26 359 | 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