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.
Code
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
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
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 =`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.