Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to for_each and then count them in Rust?

Tags:

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?

like image 270
yegor256 Avatar asked Sep 11 '25 19:09

yegor256


1 Answers

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}");
}
like image 147
Peng Guanwen Avatar answered Sep 14 '25 11:09

Peng Guanwen