Hi,
I was trying to implement a custom iterator for Vec, that has a alternative iteration scheme, but I lost to the borrow checker while doing so. I tried to debug the issue and turns out, I don't even know how to implement a normal iterator for Vec. So the task is basically to re-implement Vec<T>::iter_mut()
using safe code. I tried a very naive approach, keeping a mutable reference to the vector and an index, but that fails. I don't know exactly why and how to fix this. The code is on rust playground and also here:
use std::ops::IndexMut;
struct CustomIter<'a, T> {
i: usize,
v: &'a mut Vec<T>,
}
impl<'a, T> Iterator for CustomIter<'a, T> {
type Item = &'a mut T;
fn next(&mut self) -> Option<&'a mut T> {
if self.i == self.v.len() {
None
} else {
self.i += 1;
Some(self.v.index_mut(self.i - 1))
}
}
}
I am getting the following error:
error[E0495]: cannot infer an appropriate lifetime for autoref due to conflicting requirements
--> src/lib.rs:16:25
|
16 | Some(self.v.index_mut(self.i - 1))
| ^^^^^^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 11:5...
--> src/lib.rs:11:5
|
11 | / fn next(&mut self) -> Option<&'a mut T> {
12 | | if self.i == self.v.len() {
13 | | None
14 | | } else {
... |
17 | | }
18 | | }
| |_____^
note: ...so that reference does not outlive borrowed content
--> src/lib.rs:16:18
|
16 | Some(self.v.index_mut(self.i - 1))
| ^^^^^^
note: but, the lifetime must be valid for the lifetime 'a as defined on the impl at 8:6...
--> src/lib.rs:8:6
|
8 | impl<'a, T> Iterator for CustomIter<'a, T> {
| ^^
= note: ...so that the expression is assignable:
expected std::option::Option<&'a mut T>
found std::option::Option<&mut T>
Can someone enlighten me, what is going on and also how to fix CustomIter
to make it work?
Thanks a lot!