As you know, a for in
loop owns its iterator for the duration of the loop if you pass it an iterator directly, like so:
let v = vec![...];
let mut i = v.iter();
for _ in i { }
As malbarbo observes, you can instruct for
to take a reference to i
by writing i.by_ref()
. However, you can't repeat that from inside the for loop:
for _ in i.by_ref() {
for _ in i.by_ref() {
// ^ error: cannot borrow `i` as mutable
// more than once at a time [--explain E0499]
break;
}
}
Understandably, the outer for
loop must modify its iterator, so it takes a mutable reference to it, and nobody else can call mutable methods on i
anymore. We can show this problem more directly like so:
for _ in i.by_ref() {
i.next(); // same error
}
One recourse is to make the outer for
a loop
and call i.next()
directly. Is there a prettier way to have our cake (the outer for loop iterates over i
) and eat it too (we can still advance i
inside the outer loop)?