I’m obviously (by the question) new to Rust. In the following example, the compiler asks for the two borrows in x of g(...) to outlive 'static. I don’t understand why that is and how I could narrow it. I don’t actually know the lifetime of the slices (though I do know that the inner is as long as the outer). What am I missing? I read the lifetime explanation in the Rust book and several SO posts but while lifetimes are frequently asked about no discussion really answers this point (or I don’t see the match).
Here the problematic code in simplified form:
pub trait A <X>
where X: Copy
{
fn f(&mut self, x: Box<dyn Iterator<Item=&[X]>>) -> Option<X>;
fn g(&mut self, x: &[&[X]]) -> Option<X> {
self.f(Box::new(x.iter().copied().cycle()))
}
}
rustc 1.66.0
>Solution :
This happens because dyn Trait actually has a lifetime attached, which can be elided, and that would be 'static. So when you write dyn Trait the compiler sees dyn Trait + 'static. Since you are attempting to pass your x.iter().copied().cycle() into the function, that means that the resulting Iter must have a 'static lifetime. If you are explicit with the lifetimes, you will see that it compiles just fine:
pub trait A <X>
where X: Copy
{
fn f<'a, 'b>(&mut self, x: Box<dyn Iterator<Item=&'b[X]> + 'a>) -> Option<X>;
fn g<'a, 'b>(&mut self, x: &'a [&'b [X]]) -> Option<X> {
self.f(Box::new(x.iter().copied().cycle()))
}
}