std-method

Iterator::try_for_each — stop on failure

Run a fallible action for each item in sequence. A Result closure returns Ok(()) to proceed or Err to stop. Earlier side effects remain; this is not a transaction. Expected stdout (not executed): Err("empty id") ["A"] Some("C") Common mistake: Using for_each with an ignored Result or assuming previous actions are undone.

Formal Syntax & Structure

rust syntaxrust
fn try_for_each<F, R>(&mut self, f: F) -> R where Self: Sized, F: FnMut(Self::Item) -> R, R: Try<Output = ()>

Working Example

Example Snippetrust
fn main() {    let mut seen = Vec::new();    let mut ids = ["A", "", "C"].into_iter();    let result = ids.try_for_each(|id| {        if id.is_empty() { return Err("empty id"); }        seen.push(id);        Ok(())    });    println!("{result:?} {seen:?} {:?}", ids.next());}
Rust Reference