Skip to content
Tutorials Center
My learning

Topics

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).

Rust
use std::cmp::Ordering;

match 3.cmp(&5) {
    Ordering::Less => println!("less"),
    Ordering::Equal => println!("equal"),
    Ordering::Greater => println!("greater"),
}

Try it

Rust Ordering, min and max

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.

Rust A custom Ord with tie-breaking

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 Ord by hand, make PartialOrd return Some(self.cmp(other)) and keep == in agreement with cmp. Violations do not cause undefined behavior, but sorts and B-trees may misbehave.
  • Floats: f64 is not Ord. Use total_cmp (a total order that places NaN at the ends) or partial_cmp(..).unwrap() when you know there is no NaN.
  • Iterator::max/min need Ord; for floats use max_by with total_cmp.
  • Ties: Iterator::max returns the last of equal maxima, min the first.
  • Reverse is the idiomatic way to make BinaryHeap a min-heap or to sort descending by key.
  • Lexicographic: tuples, arrays, slices, Vec, String and Option compare element by element; None < Some(_).
  • Ordering is #[repr(i8)] with values -1, 0 and 1, but rely on the variants rather than the numbers.