liveBook · Manning

For_each

As explained in Learn Rust in a Month of Lunches

for_each is a Rust iterator method that applies a closure to every item and produces no meaningful result.

for_each is a Rust iterator method that runs a closure once for every item. The closure receives each item and returns nothing useful, so for_each performs an action without creating another iterator. section 8.2 section 8.3.1

Choose for_each when you want to do something with items rather than transform them into a collected result:

  • Use iter_mut().for_each(...) to change values in the existing collection through mutable references. section 8.2
  • Prefer map when each item should become a new value and continue through an iterator chain; map normally needs collect to create a collection. section 8.2

Print every number

fn main() { (1..=3).for_each(|num| println!("{num}")); } This prints 1, 2, and 3. Replacing the one-line closure with a block lets you print a message and branch on each number.

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains closure syntax, mutable iteration, and the contrast with map, but stops short of iterator internals.
Examples
Demonstrates printing ranges, changing vector values, and printing indexed characters.
What it assumes
Assumes basic Rust vectors and ranges while introducing iterators, closures, references, and mutable references.
What you can do after
Apply it via Rust iterator methods to perform an action for every item without building a new iterator.
How it connects
Connects for_each with iterators, closures, map, collect, iter_mut, and enumerate.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.