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)
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
| Parameter | Description |
|---|---|
sum / product / count |
Totals. |
fold(init, |acc, x| ...) |
Custom accumulation. |
any / all |
Short-circuiting checks. |
min / max / max_by_key / min_by |
Extremes. |
Examples
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.
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.2Run this on your computer — see “Get Started” for setup.
Related
Iterator::map, filter and filter_map· Transform and select items lazily: map each item, keep matching ones, or do both at once with filter_map.Iterator::collect· Turn an iterator into a collection: Vec, String, HashMap, HashSet, or a Result that fails on the first error.- Rust Iterators and Closures · tutorial