std-method
Iterator::fold
Start with an explicit accumulator and update it for each item. Empty input returns the initial value. The accumulator may have a different type from Item. Expected stdout (not executed): (3, 12) Common mistake: Choosing the wrong initial value for empty input.
Formal Syntax & Structure
rust syntaxrust
fn fold<B, F: FnMut(B, Self::Item) -> B>(self, init: B, f: F) -> B where Self: SizedWorking Example
Example Snippetrust
fn main() { let stats = [3, 7, 2].into_iter().fold((0, 0), |(count, total), n| (count + 1, total + n)); println!("{stats:?}");}