]> git.lizzy.rs Git - rust.git/blob - src/librustc_error_codes/error_codes/E0271.md
Rollup merge of #72674 - Mark-Simulacrum:clippy-always-test-pass, r=oli-obk
[rust.git] / src / librustc_error_codes / 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     println!("in foo");
10 }
11
12 impl Trait for i8 { type AssociatedType = &'static str; }
13
14 foo(3_i8);
15 ```
16
17 This is because of a type mismatch between the associated type of some
18 trait (e.g., `T::Bar`, where `T` implements `trait Quux { type Bar; }`)
19 and another type `U` that is required to be equal to `T::Bar`, but is not.
20 Examples follow.
21
22 Here is that same example again, with some explanatory comments:
23
24 ```compile_fail,E0271
25 trait Trait { type AssociatedType; }
26
27 fn foo<T>(t: T) where T: Trait<AssociatedType=u32> {
28 //                    ~~~~~~~~ ~~~~~~~~~~~~~~~~~~
29 //                        |            |
30 //         This says `foo` can         |
31 //           only be used with         |
32 //              some type that         |
33 //         implements `Trait`.         |
34 //                                     |
35 //                             This says not only must
36 //                             `T` be an impl of `Trait`
37 //                             but also that the impl
38 //                             must assign the type `u32`
39 //                             to the associated type.
40     println!("in foo");
41 }
42
43 impl Trait for i8 { type AssociatedType = &'static str; }
44 //~~~~~~~~~~~~~~~   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
45 //      |                             |
46 // `i8` does have                     |
47 // implementation                     |
48 // of `Trait`...                      |
49 //                     ... but it is an implementation
50 //                     that assigns `&'static str` to
51 //                     the associated type.
52
53 foo(3_i8);
54 // Here, we invoke `foo` with an `i8`, which does not satisfy
55 // the constraint `<i8 as Trait>::AssociatedType=u32`, and
56 // therefore the type-checker complains with this error code.
57 ```
58
59 To avoid those issues, you have to make the types match correctly.
60 So we can fix the previous examples like this:
61
62 ```
63 // Basic Example:
64 trait Trait { type AssociatedType; }
65
66 fn foo<T>(t: T) where T: Trait<AssociatedType = &'static str> {
67     println!("in foo");
68 }
69
70 impl Trait for i8 { type AssociatedType = &'static str; }
71
72 foo(3_i8);
73
74 // For-Loop Example:
75 let vs = vec![1, 2, 3, 4];
76 for v in &vs {
77     match v {
78         &1 => {}
79         _ => {}
80     }
81 }
82 ```