I'm trying to implement tokio's Encoder and running into trouble. Why is this not allowed?
error[E0207]: the lifetime parameter `'a` is not constrained by the impl trait, self type, or predicates
--> src/main.rs:7:6
|
7 | impl<'a> Bar for Baz {
| ^^ unconstrained lifetime parameter
fn main() {
println!("{}", A { foo: "foo" }.debugify())
}
struct Baz;
impl<'a> Bar for Baz {
type Item = A<'a>;
fn debugify(&mut self, item: Self::Item) -> String {
format!("{:?}", item)
}
}
#[derive(Debug)]
struct A<'a> {
foo: &'a str,
}
trait Bar {
type Item: std::fmt::Debug;
fn debugify(&mut self, item: Self::Item) -> String;
}
I've tried with type Item = Foo<'_> instead, and that doesn't work either. It seems to me the single method (and thus, the entire trait impl) does not actually need a lifetime constraint. Why is the compiler insisting on having one?
Because it doesn't know where the 'a is coming from. It seems like you want item: Self::Item<'_> as the debugify parameter, because only at the callsite of this function is the lifetime of the item known. That however requires Generic Associated Types, so this is not something you can do yet.
What you can do is implement the trait for &'a mut Baz instead, which is a common pattern in std for avoiding this problem.