0
struct Iter<'a, T> {
    slice: &'a [T],
}

impl<'a, T> Iterator for Iter<'a, T> {
    type Item = &'a T;

    fn next(&mut self) -> Option<Self::Item> {
        self.slice.get(0) // works
    }
}

struct MutIter<'a, T> {
    slice: &'a mut [T],
}

impl<'a, T> Iterator for MutIter<'a, T> {
    type Item = &'a mut T;

    fn next(&mut self) -> Option<Self::Item> {
        self.slice.get_mut(0) // fails
    }
}
fn main() {
    println!("Hello, world!");
}

playground link

error: lifetime may not live long enough
  --> src/main.rs:21:9
   |
17 | impl<'a, T> Iterator for MutIter<'a, T> {
   |      -- lifetime `'a` defined here
...
20 |     fn next(&mut self) -> Option<Self::Item> {
   |             - let's call the lifetime of this reference `'1`
21 |         self.slice.get_mut(0) // fails
   |         ^^^^^^^^^^^^^^^^^^^^^ associated function was supposed to return data with lifetime `'a` but it is returning data with lifetime `'1`

you can see that similar line with shared reference works.
see lines with comments // works and // fails in the above code snippet

Santhosh Kumar Tekuri
  • 3,012
  • 22
  • 22

0 Answers0