1 A type mismatched an associated type of a trait.
3 Erroneous code example:
6 trait Trait { type AssociatedType; }
8 fn foo<T>(t: T) where T: Trait<AssociatedType=u32> {
12 impl Trait for i8 { type AssociatedType = &'static str; }
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.
22 Here is that same example again, with some explanatory comments:
25 trait Trait { type AssociatedType; }
27 fn foo<T>(t: T) where T: Trait<AssociatedType=u32> {
28 // ~~~~~~~~ ~~~~~~~~~~~~~~~~~~
30 // This says `foo` can |
31 // only be used with |
33 // implements `Trait`. |
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.
43 impl Trait for i8 { type AssociatedType = &'static str; }
44 //~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
49 // ... but it is an implementation
50 // that assigns `&'static str` to
51 // the associated type.
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.
59 To avoid those issues, you have to make the types match correctly.
60 So we can fix the previous examples like this:
64 trait Trait { type AssociatedType; }
66 fn foo<T>(t: T) where T: Trait<AssociatedType = &'static str> {
70 impl Trait for i8 { type AssociatedType = &'static str; }
75 let vs = vec![1, 2, 3, 4];