Rust Reference ยท Iterators
Iterator min, max, min_by_key and max_by
Reference for finding extremes with Rust iterators: min, max, min_by, max_by, min_by_key and max_by_key, tie rules, floats and how to compare f64 safely.
min and max consume an iterator and return the smallest or largest item wrapped in an Option. The result is None for an empty iterator and Some(item) otherwise. The items must implement Ord, so integers, char, String, tuples and Option all work out of the box.
When the natural order is not what you want, min_by_key and max_by_key compare a derived key, and min_by and max_by take a full comparison closure. That is also the route for floating-point numbers, which only implement PartialOrd.
let nums = [4, 9, 2, 7]; let smallest = nums.iter().min(); // Some(2) let longest = ["a", "ccc", "bb"].iter().max_by_key(|s| s.len()); // Some("ccc")
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
fn min(self) -> Option<Self::Item> where Self::Item: Ord; fn max(self) -> Option<Self::Item> where Self::Item: Ord; fn min_by<F>(self, compare: F) -> Option<Self::Item> where F: FnMut(&Self::Item, &Self::Item) -> Ordering; fn max_by<F>(self, compare: F) -> Option<Self::Item> where F: FnMut(&Self::Item, &Self::Item) -> Ordering; fn min_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item> where F: FnMut(&Self::Item) -> B; fn max_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item> where F: FnMut(&Self::Item) -> B;
| Name | Description |
|---|---|
compare |
Closure that receives references to two items and returns an Ordering. |
f |
Closure that maps an item reference to a key; items are compared by their keys. |
Returns: Option<Self::Item>, None if the iterator yields nothing.
Errors / panics / edge cases: these methods never panic by themselves, but a closure doing partial_cmp(...).unwrap() panics on NaN. They consume the whole iterator, so an infinite iterator never returns.
Usage notes
- Tie rules: when several items are equally extreme,
max*returns the last one andmin*returns the first one. Do not rely on this when the order of ties matters to your logic; add a second key instead, such as a tuple(score, Reverse(name)). - Floats:
f32andf64are notOrd.a.total_cmp(&b)gives a full order (negative NaN lowest, positive NaN highest);partial_cmpreturnsNonefor NaN. - Keys are computed once per comparison step.
max_by_keyevaluates the key closure once per item, not twice per comparison, so an expensive key is acceptable. Cloning keys such asStringis wasteful; return a reference-derived value likes.len()when possible. - Borrowing:
iter().max()yieldsOption<&T>. Use.copied()or.cloned()first (or.into_iter()) when you need an owned value. - Reverse order:
min_by_key(|x| Reverse(key(x)))behaves like a maximum search with the first-wins tie rule ofmin. - Empty input is not an error. Chain
.unwrap_or(default)or match on the result. - Complexity: a single O(n) pass and O(1) extra memory. Sorting just to take the first element is O(n log n) and unnecessary.
- For the extreme of a
&[T]you can also useiter().min(); slices have no directminmethod.