Rust 1.99 (2024 edition) reference · Iterators

Rust Iterator::sum, fold, any and max_by_key Method

Reduce an iterator to one value: totals, counts, custom folds, checks, and minimum or maximum items.

Rust 1.99 (2024 edition)

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

fn sum<S>(self) -> S   fn fold<B, F>(self, init: B, f: F) -> B   fn any<F>(&mut self, f: F) -> bool   fn max_by_key<B, F>(self, f: F) -> Option<Self::Item>

Parameters

ParameterDescription
sum / product / count Totals.
fold(init, |acc, x| ...) Custom accumulation.
any / all Short-circuiting checks.
min / max / max_by_key / min_by Extremes.

Examples

Example 1
fn main() {
    let cart = [("mug", 2, 850), ("tea", 1, 1200)];
    let total: u32 = cart.iter().map(|(_, qty, cents)| qty * cents).sum();
    let items = cart.iter().fold(0, |acc, (_, qty, _)| acc + qty);
    println!("{items} items, {total} cents");
    println!("{} {}", cart.iter().any(|(n, ..)| *n == "tea"), cart.iter().all(|(_, q, _)| *q > 1));
}

Output

3 items, 2900 cents
true false

Run this on your computer — see “Get Started” for setup.

Max by key, and floats with fold
fn main() {
    let words = ["kiwi", "banana", "fig"];
    println!("{:?} {:?}", words.iter().max_by_key(|w| w.len()), words.iter().min());
    let temps = [21.5_f64, 19.0, 23.2];
    let hottest = temps.iter().cloned().fold(f64::MIN, f64::max);
    println!("{hottest}");
}

Output

Some("banana") Some("banana")
23.2

Run this on your computer — see “Get Started” for setup.

Was this page helpful?