Track Running Balance With Iterator::scan

Accumulate running account balances across transaction deltas with Iterator::scan and terminate iteration immediately when a balance goes negative.

RustData Integrity

Code

snippet
fn main() {
    let deltas = [100_i32, -35, 50, -140, 25];
    let starting_balance = 20_i32;

    // scan threads mutable state and halts the stream on overdraft (None)
    let ledger: Vec<i32> = deltas
        .iter()
        .scan(starting_balance, |balance, &delta| {
            let next = *balance + delta;
            if next < 0 {
                return None;
            }
            *balance = next;
            Some(next)
        })
        .collect();

    println!("starting balance: {starting_balance}");
    println!("settled balances: {ledger:?}");
    println!("halted after {} entries (of {})", ledger.len(), deltas.len());
}

Implementation flow — Track Running Balance With Iterator::scan

Track Running Balance With Iterator::scan keeps everything in the function main.

Points of care

  • Built-in APIs only, so there is no supply chain to vet.

Using it

Execution enters through signature fn main()

Output lines are prefixed (starting balance:, settled balances:, halted after), allowing readers to confirm each stage outcome from printed lines.

Key statements

.scan(starting_balance, |balance, &delta| {
    let next = *balance + delta;
    if next < 0 {
        return None;
    }
    *balance = next;
    Some(next)
})

Interactive Tools for This Topic

FAQ

What does Track Running Balance With Iterator::scan print when run?
Invoke the file as-is — the `starting balance:`, `settled balances:`, `halted after` prefixes identify which step printed each line.