How to use the same iterator twice, once for counting and once for iteration?

后端 未结 3 1148
悲哀的现实
悲哀的现实 2021-01-12 07:47

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

3条回答
  •  被撕碎了的回忆
    2021-01-12 08:26

    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).

提交回复
热议问题