Reputation: 549
How does one have a for
... in
loop borrow the iterator it is operating over? For example:
let x = vec![1, 2, 3, 4];
let i = x.iter();
for a1 in i { break; } // iterate over just one "i"
for a2 in i { break; } // continue iterating through "i" here
You can't simply give &i
to the for, because then it can't convert the &Iterator
to an Iterator
object.
Upvotes: 3
Views: 2358
Reputation: 432139
You can take a mutable reference to the iterator (&mut i
):
let x = vec![1, 2, 3, 4];
let mut i = x.iter();
for a1 in &mut i { break; }
for a2 in &mut i { break; }
This is the same as what Iterator::by_ref
does internally.
Upvotes: 1
Reputation: 11197
You can use Iterator::by_ref
to borrow the iterator and continue to use it after the borrow ends:
fn main() {
let x = vec![1, 2, 3, 4];
let mut i = x.iter();
for _ in i.by_ref() { break; } // iterate over just one "i"
for _ in i.by_ref() { break; } // continue iterating through "i" here
assert_eq!(Some(&3), i.next())
}
Upvotes: 4
Reputation: 51
All iterators have a next()
function that advances the iterator and returns an Option<Self::Item>
(that is, they return either None
or a Some
containing a value of whatever type you're iterating over. You can call this function yourself to manually increment the iterator however many times you want, which sounds like it would solve your problem in this case.
Upvotes: 1