1 A type parameter that is specified for `impl` is not constrained.
3 Erroneous code example:
9 // error: the type parameter `T` is not constrained by the impl trait, self
10 // type, or predicates [E0207]
12 <T as Default>::default()
17 Any type parameter of an `impl` must meet at least one of
18 the following criteria:
20 - it appears in the _implementing type_ of the impl, e.g. `impl<T> Foo<T>`
21 - for a trait impl, it appears in the _implemented trait_, e.g.
22 `impl<T> SomeTrait<T> for Foo`
23 - it is bound as an associated type, e.g. `impl<T, U> SomeTrait for T
24 where T: AnotherTrait<AssocType=U>`
28 Suppose we have a struct `Foo` and we would like to define some methods for it.
29 The previous code example has a definition which leads to a compiler error:
31 The problem is that the parameter `T` does not appear in the implementing type
32 (`Foo`) of the impl. In this case, we can fix the error by moving the type
33 parameter from the `impl` to the method `get`:
39 // Move the type parameter from the impl to the method
41 fn get<T: Default>(&self) -> T {
42 <T as Default>::default()
49 As another example, suppose we have a `Maker` trait and want to establish a
50 type `FooMaker` that makes `Foo`s:
55 fn make(&mut self) -> Self::Item;
64 impl<T: Default> Maker for FooMaker {
65 // error: the type parameter `T` is not constrained by the impl trait, self
66 // type, or predicates [E0207]
69 fn make(&mut self) -> Foo<T> {
70 Foo { foo: <T as Default>::default() }
75 This fails to compile because `T` does not appear in the trait or in the
78 One way to work around this is to introduce a phantom type parameter into
82 use std::marker::PhantomData;
86 fn make(&mut self) -> Self::Item;
93 // Add a type parameter to `FooMaker`
95 phantom: PhantomData<T>,
98 impl<T: Default> Maker for FooMaker<T> {
101 fn make(&mut self) -> Foo<T> {
103 foo: <T as Default>::default(),
109 Another way is to do away with the associated type in `Maker` and use an input
110 type parameter instead:
113 // Use a type parameter instead of an associated type here
115 fn make(&mut self) -> Item;
124 impl<T: Default> Maker<Foo<T>> for FooMaker {
125 fn make(&mut self) -> Foo<T> {
126 Foo { foo: <T as Default>::default() }
131 ### Additional information
133 For more information, please see [RFC 447].
135 [RFC 447]: https://github.com/rust-lang/rfcs/blob/master/text/0447-no-unused-impl-parameters.md