Error code E0207
A type, const or lifetime parameter that is specified for impl
is not
constrained.
Erroneous code example:
ⓘ
Any type or const parameter of an impl
must meet at least one of the
following criteria:
- it appears in the implementing type of the impl, e.g.
impl<T> Foo<T>
- for a trait impl, it appears in the implemented trait, e.g.
impl<T> SomeTrait<T> for Foo
- it is bound as an associated type, e.g.
impl<T, U> SomeTrait for T where T: AnotherTrait<AssocType=U>
Any unconstrained lifetime parameter of an impl
is not supported if the
lifetime parameter is used by an associated type.
Error example 1
Suppose we have a struct Foo
and we would like to define some methods for it.
The previous code example has a definition which leads to a compiler error:
The problem is that the parameter T
does not appear in the implementing type
(Foo
) of the impl. In this case, we can fix the error by moving the type
parameter from the impl
to the method get
:
Error example 2
As another example, suppose we have a Maker
trait and want to establish a
type FooMaker
that makes Foo
s:
ⓘ
This fails to compile because T
does not appear in the trait or in the
implementing type.
One way to work around this is to introduce a phantom type parameter into
FooMaker
, like so:
Another way is to do away with the associated type in Maker
and use an input
type parameter instead:
Error example 3
Suppose we have a struct Foo
and we would like to define some methods for it.
The following code example has a definition which leads to a compiler error:
ⓘ
The problem is that the const parameter T
does not appear in the implementing
type (Foo
) of the impl. In this case, we can fix the error by moving the type
parameter from the impl
to the method get
:
Error example 4
Suppose we have a struct Foo
and a struct Bar
that uses lifetime 'a
. We
would like to implement trait Contains
for Foo
. The trait Contains
have
the associated type B
. The following code example has a definition which
leads to a compiler error:
ⓘ
Please note that unconstrained lifetime parameters are not supported if they are being used by an associated type.
In cases where the associated type's lifetime is meant to be tied to the the self type, and none of the methods on the trait need ownership or different mutability, then an option is to implement the trait on a borrowed type:
Additional information
For more information, please see RFC 447.