1 Any type parameter or lifetime parameter of an `impl` must meet at least one of
2 the following criteria:
4 - it appears in the _implementing type_ of the impl, e.g. `impl<T> Foo<T>`
5 - for a trait impl, it appears in the _implemented trait_, e.g.
6 `impl<T> SomeTrait<T> for Foo`
7 - it is bound as an associated type, e.g. `impl<T, U> SomeTrait for T
8 where T: AnotherTrait<AssocType=U>`
12 Suppose we have a struct `Foo` and we would like to define some methods for it.
13 The following definition leads to a compiler error:
18 impl<T: Default> Foo {
19 // error: the type parameter `T` is not constrained by the impl trait, self
20 // type, or predicates [E0207]
22 <T as Default>::default()
27 The problem is that the parameter `T` does not appear in the implementing type
28 (`Foo`) of the impl. In this case, we can fix the error by moving the type
29 parameter from the `impl` to the method `get`:
35 // Move the type parameter from the impl to the method
37 fn get<T: Default>(&self) -> T {
38 <T as Default>::default()
45 As another example, suppose we have a `Maker` trait and want to establish a
46 type `FooMaker` that makes `Foo`s:
51 fn make(&mut self) -> Self::Item;
60 impl<T: Default> Maker for FooMaker {
61 // error: the type parameter `T` is not constrained by the impl trait, self
62 // type, or predicates [E0207]
65 fn make(&mut self) -> Foo<T> {
66 Foo { foo: <T as Default>::default() }
71 This fails to compile because `T` does not appear in the trait or in the
74 One way to work around this is to introduce a phantom type parameter into
78 use std::marker::PhantomData;
82 fn make(&mut self) -> Self::Item;
89 // Add a type parameter to `FooMaker`
91 phantom: PhantomData<T>,
94 impl<T: Default> Maker for FooMaker<T> {
97 fn make(&mut self) -> Foo<T> {
99 foo: <T as Default>::default(),
105 Another way is to do away with the associated type in `Maker` and use an input
106 type parameter instead:
109 // Use a type parameter instead of an associated type here
111 fn make(&mut self) -> Item;
120 impl<T: Default> Maker<Foo<T>> for FooMaker {
121 fn make(&mut self) -> Foo<T> {
122 Foo { foo: <T as Default>::default() }
127 ### Additional information
129 For more information, please see [RFC 447].
131 [RFC 447]: https://github.com/rust-lang/rfcs/blob/master/text/0447-no-unused-impl-parameters.md