Stop Accumulating Early With try_fold

try_fold takes a closure returning Result: the first failing element aborts the whole fold, while plain fold has no early-exit channel.

RustForm Validation

Code

rustsnippet
24 lines
fn main() {
    let amounts: [i64; 5] = [1200, 350, 9999, 480, 2200];

    // try_fold:闭包返回 Result,任一 Err 提前终止整个累加
    let total = amounts
        .into_iter()
        .try_fold(0i64, |acc, n| {
            if n > 5000 {
                Err(format!("single amount over budget: {n}"))
            } else {
                Ok(acc + n)
            }
        });
    println!("total = {:?}", total); // Err:9999 超预算,后面的元素不再处理

    // 全部合法时得到 Ok 累计值
    let small = [1200, 350, 480];
    let sum = small.into_iter().try_fold(0i64, |acc, n| Ok(acc + n));
    println!("sum = {:?}", sum);

    // 对比:普通 fold 没有"提前退出"通道,违规只能事后补救
    let naive: i64 = amounts.into_iter().fold(0, |acc, n| acc + n);
    println!("naive fold = {naive}");
}

How the snippet works

Stop Accumulating Early With try_fold is built around the function main.

Applying it

Running the file prints labeled results such as total =, sum =, naive fold = — each operation’s effect is visible in the output.

Statements that matter

let sum = small.into_iter().try_fold(0i64, |acc, n| Ok(acc + n));
let naive: i64 = amounts.into_iter().fold(0, |acc, n| acc + n);
Err(format!("single amount over budget: {n}"))
} else {
Ok(acc + n)
}

Interactive Tools for This Topic

FAQ

What does Stop Accumulating Early With try_fold print when run?
The script runs standalone; its 3 labeled outputs include `total =`, `sum =`, `naive fold =`.