Iterator Sum On Results Short-Circuits

Iterator::sum works on Result items too: Ok values accumulate and the first Err stops the fold, so a dirty row surfaces with its context.

RustResilience

Code

rustsnippet
17 lines
fn parse_ms(raw: &str) -> Result<u64, String> {
    raw.parse::<u64>().map_err(|e| format!("{raw}: {e}"))
}

fn main() {
    let rows = ["120", "40", "7"];

    // the Sum impl for Result: Ok values accumulate one by one, and the first Err short-circuits
    let total: Result<u64, String> = rows.iter().map(|row| parse_ms(row)).sum();
    println!("total: {total:?}");

    let dirty = ["120", "oops", "7"];

    // the error surfaces with the bad line's context and the remaining lines are never parsed
    let stopped: Result<u64, String> = dirty.iter().map(|row| parse_ms(row)).sum();
    println!("stopped: {stopped:?}");
}

What the code does

Every runnable line is contained in the functions parse_ms and main.

Fallible operations return Result, forcing the caller to handle both arms explicitly.

Caveats

  • All behavior comes from the standard library; nothing is external.
  • Errors travel through Result; if you drop the ? operators while adapting, each call site needs its own match.

Using it

Signature: fn parse_ms(raw: &str) -> Result<u64, String>

The run emits 2 labeled sections — total:, stopped: — one per step.

The entry point wires parse_ms together — run it once and the whole demo flows.

Key statements

let stopped: Result<u64, String> = dirty.iter().map(|row| parse_ms(row)).sum();
let total: Result<u64, String> = rows.iter().map(|row| parse_ms(row)).sum();
fn parse_ms(raw: &str) -> Result<u64, String> {
    raw.parse::<u64>().map_err(|e| format!("{raw}: {e}"))
}

Interactive Tools for This Topic

FAQ

How are errors reported?
Each fallible operation returns `Result`; nothing is silently discarded.
What does Iterator Sum On Results Short-Circuits print when run?
The script runs standalone; its 2 labeled outputs include `total:`, `stopped:`.