std-method

Iterator::reduce

Combine values using the first item as the initial accumulator. Empty input gives None, and the accumulator has the item type. Expected stdout (not executed): Some(8) None Common mistake: Unwrapping the result without establishing nonempty input.

Formal Syntax & Structure

rust syntaxrust
fn reduce<F: FnMut(Self::Item, Self::Item) -> Self::Item>(self, f: F) -> Option<Self::Item> where Self: Sized

Working Example

Example Snippetrust
fn main() {    let cheapest = [14, 8, 11].into_iter().reduce(i32::min);    let empty = (0..0).reduce(i32::min);    println!("{cheapest:?} {empty:?}");}
Rust Reference