]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_error_codes/src/error_codes/E0271.md
Rollup merge of #92310 - ehuss:rustdoc-ice, r=estebank
[rust.git] / compiler / rustc_error_codes / src / error_codes / E0271.md
1 A type mismatched an associated type of a trait.
2
3 Erroneous code example:
4
5 ```compile_fail,E0271
6 trait Trait { type AssociatedType; }
7
8 fn foo<T>(t: T) where T: Trait<AssociatedType=u32> {
9 //                    ~~~~~~~~ ~~~~~~~~~~~~~~~~~~
10 //                        |            |
11 //         This says `foo` can         |
12 //           only be used with         |
13 //              some type that         |
14 //         implements `Trait`.         |
15 //                                     |
16 //                             This says not only must
17 //                             `T` be an impl of `Trait`
18 //                             but also that the impl
19 //                             must assign the type `u32`
20 //                             to the associated type.
21     println!("in foo");
22 }
23
24 impl Trait for i8 { type AssociatedType = &'static str; }
25 //~~~~~~~~~~~~~~~   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
26 //      |                             |
27 // `i8` does have                     |
28 // implementation                     |
29 // of `Trait`...                      |
30 //                     ... but it is an implementation
31 //                     that assigns `&'static str` to
32 //                     the associated type.
33
34 foo(3_i8);
35 // Here, we invoke `foo` with an `i8`, which does not satisfy
36 // the constraint `<i8 as Trait>::AssociatedType=u32`, and
37 // therefore the type-checker complains with this error code.
38 ```
39
40 The issue can be resolved by changing the associated type:
41 1) in the `foo` implementation:
42 ```
43 trait Trait { type AssociatedType; }
44
45 fn foo<T>(t: T) where T: Trait<AssociatedType = &'static str> {
46     println!("in foo");
47 }
48
49 impl Trait for i8 { type AssociatedType = &'static str; }
50
51 foo(3_i8);
52 ```
53
54 2) in the `Trait` implementation for `i8`:
55 ```
56 trait Trait { type AssociatedType; }
57
58 fn foo<T>(t: T) where T: Trait<AssociatedType = u32> {
59     println!("in foo");
60 }
61
62 impl Trait for i8 { type AssociatedType = u32; }
63
64 foo(3_i8);
65 ```