yegor256
yegor256

Reputation: 105053

How to for_each and then count them in Rust?

I'm trying to go through an iterator, select certain elements, do something with each of them, and then count how many of them were affected:

let done = foo
  .into_iter()
  .filter(...)
  .for_each(|i| do_something_with(i))
  .len();

This doesn't work since for_each doesn't return an iterator. The best option I found so far is this:

let mut done = 0;
foo
  .into_iter()
  .filter(...)
  .for_each(|i| { do_something_with(i); done += 1; });

Maybe there is a more elegant immutable one?

Upvotes: 3

Views: 1820

Answers (1)

Peng Guanwen
Peng Guanwen

Reputation: 722

If you want to do something on each element, but do not consume ownership of the elements, then Iterator::inspect is the method to use.

Another problem in your code is that Iterator::count should be used instead of ExactSizeIterator::len.

Example code:

use core::fmt::Debug;

fn do_something_with(i: impl Debug) {
    println!("{:?}", i);
}

fn main() {
    let foo = [1, 2, 3];
    let done: usize = foo
        .into_iter()
        .filter(|x| x % 2 == 1)
        .inspect(|i| do_something_with(i))
        .count();
    
    println!("{done}");
}

Upvotes: 8

Related Questions