Is there a shorthand for counting items in an iterator that satisfy a predicate?

I can do this via fold:

  let count = input
    .iter()
    .fold(0, |acc, item| if predicate(&item) { acc + 1 } else { acc });

However, I feel like this is a fairly common goal and I might be overcomplicating it. Is there something in the stdlib that allows doing the above with an interface that is closer to this?

  let count = input
    .iter()
    .count_if(|item| predicate(&item));

I think input.iter().filter(predicate).count() will work.

8 Likes

Thanks! That indeed works and much nicer to read. For the record, I benchmarked both solutions (predicate and data being the same) and found that both performed roughly the same (within .1 ms of each other per run).

1 Like

This is absolutely the right way...

...as the code handles it specifically to be fast:

1 Like