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