It seems that an iterator is consumed when counting. How can I use the same iterator for counting and then iterate on it?
I\'m trying to count the lines in a file an
Calling count
consumes the iterator, because it actually iterates until it is done (i.e. next()
returns None
).
You can prevent consuming the iterator by using by_ref
, but the iterator is still driven to its completion (by_ref
actually just returns the mutable reference to the iterator, and Iterator
is also implemented for the mutable reference: impl<'a, I> Iterator for &'a mut I
).
This still can be useful if the iterator contains other state you want to reuse after it is done, but not in this case.
You could simply try forking the iterator (they often implement Clone
if they don't have side effects), although in this case recreating it is just as good (most of the time creating an iterator is cheap; the real work is usually only done when you drive it by calling next
directly or indirectly).
So no, (in this case) you can't reset it, and yes, you need to create a new one (or clone it before using it).