std-method
Iterator::try_fold — checked accumulation
Combine items until the closure reports failure or the source ends. With Option, None stops the fold; the failing item is consumed and remaining items are available. The Try bound is part of the public signature, but implementing Try yourself is unstable on the proposed baseline. Expected stdout (not executed): None Some(7) Common mistake: Assuming the iterator restarts or the accumulator is automatically returned on failure.
Formal Syntax & Structure
rust syntaxrust
fn try_fold<B, F, R>(&mut self, init: B, f: F) -> R where Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Output = B>Working Example
Example Snippetrust
fn main() { let mut amounts = [10_u8, 250, 7].into_iter(); let total = amounts.try_fold(0_u8, |acc, n| acc.checked_add(n)); println!("{total:?} {:?}", amounts.next());}