Iterator where Item<'a>

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

F: for<'a> FnMut(Self::Item<'a>) works.

1 Like

I did that and it has the same effect as putting the '_ but the problem is that I still cannot pass my short lived item

How so? It compiles just fine.

I think this falls under the known GAT limitations, which specifically mentions for_each:

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.