for_each_count

Crates.iofor_each_count
lib.rsfor_each_count
version0.1.0
created_at2025-07-15 14:25:49.038128+00
updated_at2025-07-15 14:25:49.038128+00
descriptionfor_each_count and try_for_each_count extension methods for iterators
homepagehttps://github.com/glueball/for_each_count
repositoryhttps://github.com/glueball/for_each_count
max_upload_size
id1753435
size14,751
(glueball)

documentation

README

for_each_count

Extremely simple crate providing an extension trait for the standard [Iterator] trait with two utility methods:

Both methods solve the common1 use case of applying a transformation to iterator elements and then returning the length of the iterator. While this is trivial to achieve using the standard methods2, I find these extension methods to be more ergonomic, and they are available in the big extension crates, like Itertools.

The provided extension methods try to mimic the way they'd be likely implemented in core: based on fold() and try_fold(). This seems to be the preferred strategy in the standard library. for_each(), try_for_each() and count() are all implemented like this at this time.

Examples

use for_each_count::IteratorForEachCount;

let mut sum = 0;
let count = (1..=5).for_each_count(|x| sum += x);
assert_eq!(count, 5);
assert_eq!(sum, 15);

Footnotes

  1. Maybe not that common, but I've needed it a couple of times. Other people too.

  2. Like using [Iterator::inspect], or [Iterator::map] and [Iterator::count], or keeping a mutable count outside the closure passed to for_each.

Commit count: 0

cargo fmt