Hey there,
I just ran into a borrow-checker problem which I cannot solve. I got an Iter
and IterMut
implementation for a custom collection type. Both implementation use equivalent code, just the type of the reference is changed. And somehow, the immutable version compiles, while the mutable does not.
I simplified to code, still resulting in basically the same error message (Playground)
/// Iterator over immutable references, compiles
pub struct Iter<'a, T> {
source: &'a Vec<T>,
next_index: usize,
}
impl<'a, T> Iterator for Iter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
if let Some(value) = self.source.get(self.next_index) {
self.next_index += 1;
Some(value)
} else {
None
}
}
}
// Iterator over mutable references, does not compile
pub struct IterMut<'a, T> {
source: &'a mut Vec<T>,
next_index: usize,
}
impl<'a, T> Iterator for IterMut<'a, T> {
type Item = &'a mut T;
fn next(&mut self) -> Option<Self::Item> {
if let Some(value) = self.source.get_mut(self.next_index) {
self.next_index += 1;
Some(value)
} else {
None
}
}
}
Error message:
error: lifetime may not live long enough
--> src/lib.rs:32:13
|
26 | impl<'a, T> Iterator for IterMut<'a, T> {
| -- lifetime `'a` defined here
...
29 | fn next(&mut self) -> Option<Self::Item> {
| - let's call the lifetime of this reference `'1`
...
32 | Some(value)
| ^^^^^^^^^^^ method was supposed to return data with lifetime `'a` but it is returning data with lifetime `'1`
If I comment out IterMut
, the code compiles.
I even tried to add the 'a
lifetime to self, but that does not seem to change anything. The compiler still tells me, that self is '1
impl<'a, T> Iterator for IterMut<'a, T> where Self: 'a
It would be great, if someone could help me in solving this error. It is not obvious to me, why the mutable version should not work. Thanks in advance