2023-05-24

Lifetime problem with Iterator implementation

I'm getting this lifetime error from the rust compiler. I would like to know how to change the next method to make it work.

error: lifetime may not live long enough
   --> src/sequence.rs:154:9
    |
138 | impl<'a, T, S> Iterator for Sequence<'a, T, S>
    |      -- lifetime `'a` defined here
...
144 |     fn next(&mut self) -> Option<Self::Item> {
    |             - let's call the lifetime of this reference `'1`
...
154 |         self.nth_element(iter_index)
    |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ method was supposed to return data with lifetime `'a` but it is returning data with lifetime `'1`

The code:

impl<'a, T, S> Iterator for Sequence<'a, T, S>
where
    Self: 'a,
{
    type Item = &'a T;

    fn next(&mut self) -> Option<Self::Item> {
        let iter_index = self.iter_index;

        if iter_index >= self.len() {
            self.iter_index = 0;
            return None;
        }

        self.iter_index += 1;

        self.nth_element(iter_index)
    }
}

The full source code



No comments:

Post a Comment