I need a lifetime parameter for the following trait because I want the actual type of the Iterator (e.g. Iter of slice contains has a lifetime parameter). It can't be a method lifetime parameter, because the return type depends on it.
pub trait Iterable<'a> {
type Iter: Iterator;
fn iterate(&'a self) -> Self::Iter;
}
To simplify things, I will use the following trait:
trait Test<'a> {}
I want to use this trait in a function like this function:
fn test<I>(t: I)
where
for<'a> I: Test<'a>,
{
{
// First use of t
}
{
// Second use of t
}
}
So far so good, if I impl this trait for any normal type the function works as expected.
But if I try to use a type containing a reference, the compiler complains that it needs to borrow the value for 'static.
This is kinda unexpected since I don't even use the value nor return anything. The problem is obviously for<'a> but I see no other way to tell the compiler "I implements the trait for every lifetime that is within the function scope" since I can't restrict the lifetime 'a. Furthermore, I can't make 'a a lifetime parameter of test because this would mean I would be borrowed for 'a after the first use, which is longer than the scope of the function.
Minimal failing example would be
struct ContainingReference<'a>(&'a i32);
// Implement the trait for every lifetime that is at most as long as 'a
impl<'a: 'b, 'b> Test<'b> for ContainingReference<'a> {}
fn main() {
let i = 0;
test(ContainingReference(&i));
}
error[E0597]: `i` does not live long enough
|
| t(ContainingReference(&i));
| ----------------------^^--
| | |
| | borrowed value does not live long enough
| argument requires that `i` is borrowed for `'static`
...
| }
| - `i` dropped here while still borrowed