I need an iterator with lifetime, so I did this:
pub trait LendingIterator {
type Item<'a>
where
Self: 'a;
fn next<'a>(&'a mut self) -> Option<Self::Item<'a>>;
fn for_each<'a, F>(
mut self,
mut f: F,
) where
Self: Sized + 'a,
F: FnMut(Self::Item<'a>),
{
while let Some(x) = self.next() {
f(x);
}
}
}
but I get
error[E0499]: cannot borrow `self` as mutable more than once at a time
--> src/lib.rs:15:23
|
8 | fn for_each<'a, F>(
| -- lifetime `'a` defined here
...
15 | while let Some(x) = self.next() {
| ^^^^^^^^^^^
| |
| `self` was mutably borrowed here in the previous iteration of the loop
| argument requires that `self` is borrowed for `'a`
For more information about this error, try `rustc --explain E0499`.
error: could not compile `playground` due to previous error
and I don't know exactly why. If I deactivate the f(x)
call it works so I think f
is somehow borrowed for the entire lifetime 'a
, which is strange since f
is moved.
Anyways, how can I solve this?
PS:
F: FnMut(Self::Item<'_>),
solves the problem but forces F
to have a static lifetime so I cannot call it with short living stuff