]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_error_codes/src/error_codes/E0222.md
Rollup merge of #93556 - dtolnay:trailingcomma, r=cjgillot
[rust.git] / compiler / rustc_error_codes / src / error_codes / E0222.md
1 An attempt was made to constrain an associated type.
2
3 Erroneous code example:
4
5 ```compile_fail,E0222
6 pub trait Vehicle {
7     type Color;
8 }
9
10 pub trait Box {
11     type Color;
12 }
13
14 pub trait BoxCar : Box + Vehicle {}
15
16 fn dent_object<COLOR>(c: dyn BoxCar<Color=COLOR>) {} // Invalid constraint
17 ```
18
19 In this example, `BoxCar` has two supertraits: `Vehicle` and `Box`. Both of
20 these traits define an associated type `Color`. `BoxCar` inherits two types
21 with that name from both supertraits. Because of this, we need to use the
22 fully qualified path syntax to refer to the appropriate `Color` associated
23 type, either `<BoxCar as Vehicle>::Color` or `<BoxCar as Box>::Color`, but this
24 syntax is not allowed to be used in a function signature.
25
26 In order to encode this kind of constraint, a `where` clause and a new type
27 parameter are needed:
28
29 ```
30 pub trait Vehicle {
31     type Color;
32 }
33
34 pub trait Box {
35     type Color;
36 }
37
38 pub trait BoxCar : Box + Vehicle {}
39
40 // Introduce a new `CAR` type parameter
41 fn foo<CAR, COLOR>(
42     c: CAR,
43 ) where
44     // Bind the type parameter `CAR` to the trait `BoxCar`
45     CAR: BoxCar,
46     // Further restrict `<BoxCar as Vehicle>::Color` to be the same as the
47     // type parameter `COLOR`
48     CAR: Vehicle<Color = COLOR>,
49     // We can also simultaneously restrict the other trait's associated type
50     CAR: Box<Color = COLOR>
51 {}
52 ```