Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is a static lifetime asked for and how can I narrow it when dealing with rust Iterators?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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()))
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading