Using an iterator to tabulate statistics

I am using an iterator to tabulate some statistics about the data it traverses over. I ran into a problem that calling map() or using a "for loop" moves the iterator, so that it is not possible to get at the saved statistics.

Are there workaround to this problem? Do I have to create this iterator passing in a mutable reference of the stat holder?

If I is an iterator, then &mut I is also an iterator that just defers to I's implementation. So within a function body (for example) you can replace

for item in iterator { /* ... */ }
// Moved :-(
// let stats = iterator.stats();


for item in &mut iterator { /* ... */ }
let stats = iterator.stats(); // Still there :-)

And you can do something similar for the map, but you won't be able to create a map containing the &mut and return it up a call stack, say. So something more involved may be called for depending on your use case.


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.