try_for_each Stops On The First Err

try_for_each folds a fallible closure over an iterator and returns on the first Err, so later items are never touched after a failure.

RustData Integrity

Code

rustsnippet
28 lines
fn validate(name: &str) -> Result<(), String> {
    if name.is_empty() {
        return Err(String::from("empty name"));
    }
    if !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') {
        return Err(format!("invalid character in {name}"));
    }
    Ok(())
}

fn main() {
    let queue = ["build-1", "build-2", "bad/name", "build-3"];

    // try_for_each short-circuits on the first Err: elements after the failure are never touched
    let outcome: Result<(), String> = queue.iter().try_for_each(|name| {
        println!("checking {name}");
        validate(name)
    });

    match outcome {
        Ok(()) => println!("all valid"),
        Err(problem) => println!("stopped at: {problem}"),
    }

    // When everything validates it collapses into Ok
    let clean = ["a", "b-c"];
    println!("clean run: {:?}", clean.iter().try_for_each(|n| validate(n)));
}

How the snippet works

try_for_each Stops On The First Err comes down to the functions validate and main.

Result is the error channel: the caller receives the failure as a value instead of an exception. Each possible shape of the input gets its own match arm, and the compiler checks the set is complete.

What to watch for

  • Result is the only error channel — remove a ? while adapting and that site needs an explicit match.

Applying it

The main signature reads fn validate(name: &str) -> Result<(), String>

Running the file prints labeled results such as checking, all valid, stopped at: — each operation’s effect is visible in the output.

Running the file executes main, which drives validate in order.

Statements that matter

return Err(format!("invalid character in {name}"));
return Err(String::from("empty name"));
let outcome: Result<(), String> = queue.iter().try_for_each(|name| {
println!("checking {name}");
validate(name)
});

Interactive Tools for This Topic

FAQ

How should callers handle failures?
No panics — `Result` values carry the failure.
What does try_for_each Stops On The First Err print when run?
Invoke the file as-is — the `checking`, `all valid`, `stopped at:` prefixes identify which step printed each line.