I have iterator implementations, where the first one returns immutable reference to the buffer and the second one returns mutable reference to the buffer.
When I compile the code, the mutable version fails to compile with "error: lifetime may not live long enough".
I understand the possible danger of this code(let's suppose that there was a bug so same index's mutable reference has been returned twice), but I can't understand how the compiler figures lifetime in this code.
Anybody willing to explain how the compiler rejects the second version, while accepting the first version?
pub struct Iter<'a, T> {
buffer: &'a [T],
position: usize,
remaining: usize,
}
impl<'a, T> Iterator for Iter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
if self.remaining == 0 {
return None;
}
let len = self.buffer.len();
let item = &self.buffer[self.position];
self.position = (self.position + 1) % len;
self.remaining -= 1;
Some(item)
}
}
pub struct IterMut<'a, T> {
buffer: &'a mut [T],
position: usize,
remaining: usize,
}
impl<'a, T> Iterator for IterMut<'a, T> {
type Item = &'a mut T;
fn next(&mut self) -> Option<Self::Item> {
if self.remaining == 0 {
return None;
}
let len = self.buffer.len();
let item = &mut self.buffer[self.position];
self.position = (self.position + 1) % len;
self.remaining -= 1;
Some(item)
}
}