for_each Consumes Iterators With Side Effects

Iterator::for_each runs a closure with captured mutable state over a consumed iterator, keeping chained adapters lazy until it executes.

RustData Integrity

Code

rustsnippet
23 lines
use std::collections::HashMap;

fn main() {
    let orders = vec![("alpha", 3), ("beta", 5), ("gamma", 2)];

    // for_each consumes iterators: the closure owns the mutable state
    let mut totals: HashMap<&str, i32> = HashMap::new();
    orders.iter().for_each(|&(name, qty)| {
        *totals.entry(name).or_insert(0) += qty;
    });
    println!("totals: {totals:?}");

    // enumerate gives indexed side effects without a manual counter
    orders.iter().enumerate().for_each(|(i, (name, _))| {
        println!("{i}: shipping {name}");
    });

    // chained adapters stay lazy until for_each drives them
    orders
        .iter()
        .filter(|(_, q)| *q >= &3)
        .for_each(|(n, q)| println!("big order: {n} x {q}"));
}

How it works

for_each Consumes Iterators With Side Effects reduces to the function main.

Watch out for

  • Nothing sits in the dependency list; the runtime itself supplies it all.

Putting it to use

The signature doing the primary work is fn main()

Output lines are prefixed (totals:, big order:), so each step’s effect shows up clearly in the output.

Core lines under the microscope

orders.iter().enumerate().for_each(|(i, (name, _))| {
    println!("{i}: shipping {name}");
});
orders.iter().for_each(|&(name, qty)| {
    *totals.entry(name).or_insert(0) += qty;
});
.filter(|(_, q)| *q >= &3)
.for_each(|(n, q)| println!("big order: {n} x {q}"));

Interactive Tools for This Topic

FAQ

What does for_each Consumes Iterators With Side Effects print when run?
Running the file directly is enough — expect labeled output lines such as `totals:`, `big order:`.