std-method

Iterator::for_each

Drive a finite iterator for effects instead of collecting a result. Use a for loop when explicit break or continue improves clarity. Expected stdout (not executed): status=packed status=shipped Common mistake: Trying to use break inside the closure to exit iteration.

Formal Syntax & Structure

rust syntaxrust
fn for_each<F: FnMut(Self::Item)>(self, f: F) where Self: Sized

Working Example

Example Snippetrust
fn main() {    ["packed", "shipped"].into_iter().for_each(|state| println!("status={state}"));}
Rust Reference