In Rust, you can loop through collections like Vec, HashMap, or arrays using the .iter() method combined with .for_each(). The for_each method takes a closure (anonymous function) and applies it to each element in the collection.

This article shows some common examples of using for_each in Rust.

1. Basic for_each with Vec

fn main() {
    let names = vec!["Alice", "Bob", "Charlie"];

    names.iter().for_each(|name| println!("Hello, {}", name));
}

Output:

Hello, Alice
Hello, Bob
Hello, Charlie
  • .iter() returns an iterator over the vector.

  • .for_each(|name| ...) applies the closure to each element.

  • We use println! inside the closure to print each name.

2. for_each with index using enumerate()

fn main() {
    let items = vec!["Apple", "Banana", "Orange"];

    items.iter().enumerate().for_each(|(index, item)| {
        println!("Item {}: {}", index, item);
    });
}

Output:

Item 0: Apple
Item 1: Banana
Item 2: Orange
  • .enumerate() adds an index to each item.

  • Closure receives a tuple (index, item).

3. for_each with mutable vector

fn main() {
    let mut numbers = vec![1, 2, 3];

    numbers.iter_mut().for_each(|num| *num *= 10);

    println!("{:?}", numbers);
}

Output:

[10, 20, 30]
  • .iter_mut() gives mutable references.

  • We dereference each num and multiply it by 10.

4. for_each on a HashMap

use std::collections::HashMap;

fn main() {
    let mut map = HashMap::new();
    map.insert("a", 1);
    map.insert("b", 2);
    map.insert("c", 3);

    map.iter().for_each(|(key, value)| {
        println!("Key: {}, Value: {}", key, value);
    });
}

Output:

Key: a, Value: 1
Key: b, Value: 2
Key: c, Value: 3
  • .iter() returns key-value pairs from the map.

  • Closure receives (key, value).

5. Chaining filter and for_each

fn main() {
    let numbers = vec![1, 2, 3, 4, 5, 6];

    numbers.iter()
        .filter(|&n| n % 2 == 0)
        .for_each(|n| println!("Even: {}", n));
}

Output:

Even: 2
Even: 4
Even: 6
  • .filter() selects even numbers.

  • .for_each() prints each even number.

In Rust, the for_each method is a clean and functional way to iterate over collections. It works well with iterators and can be combined with other methods like enumerate, filter, or map. Use .iter() for read-only access and .iter_mut() for mutable references.

Happy Learning 🙂

References: