Rust Reference ยท Standard Library Modules
The std::cmp module
Reference for Rust std::cmp: PartialEq, Eq, PartialOrd, Ord, the Ordering enum, min, max, min_by_key, Reverse and clamp, with sorting examples.
std::cmp contains the traits that define equality and ordering (PartialEq, Eq, PartialOrd, Ord), the Ordering enum their comparisons return, helper functions (min, max and their _by/_by_key variants) and the Reverse wrapper.
The traits come in a "partial" and a "total" pair. PartialEq and PartialOrd allow values that are not comparable (the classic case is f64::NAN), while Eq and Ord promise a complete, consistent order. Sorting, BTreeMap keys and BinaryHeap items need Ord; HashMap keys need Eq (plus Hash).
use std::cmp::Ordering; match 3.cmp(&5) { Ordering::Less => println!("less"), Ordering::Equal => println!("equal"), Ordering::Greater => println!("greater"), }
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
| Item | Description |
|---|---|
PartialEq<Rhs = Self> |
eq, ne. Powers == and !=. Symmetric and transitive, but not necessarily reflexive. |
Eq |
Marker: equality is also reflexive. Derivable. |
PartialOrd<Rhs = Self> |
partial_cmp returning Option<Ordering>, plus lt, le, gt, ge. |
Ord |
cmp returning Ordering, plus max, min, clamp. |
Ordering |
Less, Equal, Greater; methods reverse, then, then_with, is_lt, is_le, is_gt, is_ge, is_eq, is_ne. |
min(a, b), max(a, b) |
Return the smaller or larger; on a tie, min returns the first and max the second. |
min_by, max_by, min_by_key, max_by_key |
Same with a comparator or key function. |
Reverse<T> |
Tuple struct that flips Ord. |
Usage notes
- Deriving:
#[derive(PartialOrd, Ord)]compares fields in declaration order (and enum variants in declaration order). Put the most significant field first. - Consistency rule: if you implement
Ordby hand, makePartialOrdreturnSome(self.cmp(other))and keep==in agreement withcmp. Violations do not cause undefined behavior, but sorts and B-trees may misbehave. - Floats:
f64is notOrd. Usetotal_cmp(a total order that placesNaNat the ends) orpartial_cmp(..).unwrap()when you know there is noNaN. Iterator::max/minneedOrd; for floats usemax_bywithtotal_cmp.- Ties:
Iterator::maxreturns the last of equal maxima,minthe first. Reverseis the idiomatic way to makeBinaryHeapa min-heap or to sort descending by key.- Lexicographic: tuples, arrays, slices,
Vec,StringandOptioncompare element by element;None < Some(_). Orderingis#[repr(i8)]with values -1, 0 and 1, but rely on the variants rather than the numbers.
Related
std::collections,std::iter,std::ops- Lessons: Sorting and searching, Traits, Operators