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.
