How to Use fold and reduce in Rust

Use fold to accumulate values with a starting point and reduce to combine all elements into a single result without an initial value.

Use fold to accumulate a value by iterating over a collection and reduce to combine all elements into a single value without an initial accumulator.

let numbers = vec![1, 2, 3, 4];

// fold: starts with 0, adds each number
let sum_fold: i32 = numbers.iter().fold(0, |acc, &x| acc + x);

// reduce: combines elements pairwise, no initial value
let sum_reduce: Option<i32> = numbers.iter().reduce(|acc, &x| acc + x);

println!("Fold: {}, Reduce: {:?}", sum_fold, sum_reduce);