Combining `Iterator::scan` and `Iterator::fold`


I would like to get the final state held by std::iter::Scan, while still being able to access the intermediate values produced by that iterator. Without getting too much into details, I’d like to have something similar to (20..30).enumerate(), use that values it produces, and once it’s exhausted, also have a way to get the total item count, i.e. 10. Is there a way to do that, or some idiomatic way to achieve the same thing?


How about inspect()?

let mut count = 0;
for x in (20..30).inspect(|_| count += 1).enumerate() { ... }

But I don’t see why fold is problematic on its own.


Consider making a PR to propose an into_state() method (or something). It seems reasonable to me, so probably worth seeing what libs has to say about it.


How would you package this up as an interface? I want to give the caller something that is both an iterator and gives access to the final state. Also, notice that this snippet has code duplication: the closure and enumerate both do the same computation. It’s not a big problem here, but my actual use case involves a more complicated computation, and I don’t want to do it twice.


I wouldn’t rush it, I think this is a pattern that appears in several places in the library, it’s probably better to give it some more thought.