How to use fold and reduce

Use fold to accumulate values with a starting point and reduce to combine iterator items into a single result.

Use fold to accumulate a value from an iterator into a new type, and reduce to combine all items in an iterator into a single item of the same type. fold requires an initial value, while reduce uses the first item as the starting point and returns None if the iterator is empty.

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

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

// reduce: starts with first item, adds remaining, returns Some(10)
let product = numbers.iter().reduce(|acc, &x| acc * x);