I've reduced my problem to the following code:
struct Struct<'a, 'b, T> {
a: &'a T,
b: &'b T,
}
trait Trait<'a, 'b, T> {
fn a(&self) -> &'a T;
fn b(&self) -> &'b T;
}
impl<'a, 'b, T> Trait<'a, 'b, T> for Struct<'a, 'b, T> {
fn a(&self) -> &'a T {
self.a
}
fn b(&self) -> &'b T {
self.b
}
}
struct Confused<T> {
field: T,
}
impl<T> Confused<T> {
fn foo<'a, 'b>(&'a self, param: &Struct<'a, 'b, T>) -> &'a T {
param.b();
param.a()
}
fn bar<'a, 'b, U: Trait<'a, 'b, T>>(&'a self, param: &U) -> &'a T {
param.b();
param.a()
}
}
The function foo
is okay, but when I replace the concrete type Struct<'a, 'b, T>
with a generic type U: Trait<'a, 'b, T>
, I get the following error:
error[E0309]: the parameter type `T` may not live long enough --> src/lib.rs:31:15 | 24 | impl<T> Confused<T> { | - help: consider adding an explicit lifetime bound `T: 'b`... ... 31 | param.b(); | ^ | note: ...so that the reference type `&'b T` does not outlive the data it points at --> src/lib.rs:31:15 | 31 | param.b(); | ^
The suggestion to add the bound T: 'b
doesn't make sense to me, since 'b
is a parameter to bar()
. How can I fix bar()
to accept any implementation of Trait<'a, 'b, T>
as a parameter?