Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Core Traits

PartialOrd and Ord traits

Reference for PartialOrd and Ord in Rust: comparison operators, the Ordering enum, derive order, sort and sort_by_key, floats with total_cmp, and Reverse.

PartialOrd powers <, <=, > and >=. Its method partial_cmp returns Option<Ordering>, because some pairs have no order (comparing anything with NaN). Ord is the total version: cmp always returns an Ordering (Less, Equal or Greater). It is what sort, BTreeMap, BinaryHeap, max and min need.

Both require PartialEq, and Ord additionally requires Eq. Derive all four together for most types.

Rust
#[derive(PartialEq, Eq, PartialOrd, Ord)]
struct Version(u32, u32);

Try it

Rust Derived ordering and sorting

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 Custom order, floats and Reverse

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

Rust
pub trait PartialOrd<Rhs = Self>: PartialEq<Rhs> {
    fn partial_cmp(&self, other: &Rhs) -> Option<Ordering>;
    // lt, le, gt, ge have default methods
}

pub trait Ord: Eq + PartialOrd {
    fn cmp(&self, other: &Self) -> Ordering;
    // max, min, clamp have default methods
}
Name Description
other The value to compare with, by reference.
Ordering An enum with variants Less, Equal, Greater. It has reverse(), then() and then_with() for chaining keys.

Returns: Option<Ordering> for partial_cmp (None means unordered), Ordering for cmp.

Usage notes

  • Derive order: structs compare field by field from the first, enums by variant position (earlier declared is smaller) and then by payload. Reorder fields to change the sort key.
  • Implement Ord first, then PartialOrd as Some(self.cmp(other)). Writing both independently invites inconsistent results.
  • Consistency with Eq: a.cmp(&b) == Equal must match a == b. Collections rely on it.
  • Floats: f64 is only PartialOrd, so sort() and max() do not compile for Vec<f64>. Use sort_by(|a, b| a.total_cmp(b)) (NaN sorts to the ends) or partial_cmp(..).unwrap() when NaN cannot occur.
  • Multi-key sorting: a.x.cmp(&b.x).then_with(|| a.y.cmp(&b.y)), or compare tuples (a.x, a.y).cmp(&(b.x, b.y)).
  • Descending order: sort_by(|a, b| b.cmp(a)), or wrap keys in std::cmp::Reverse. A BinaryHeap is a max-heap; Reverse turns it into a min-heap.
  • Strings compare byte by byte (UTF-8 order), not by locale. "Z" < "a" is true.
  • sort_by_key calls the key function many times; sort_by_cached_key computes each key once when the key is expensive.
  • clamp, max, min are Ord methods; std::cmp::max/min are the free-function forms. For floats use f64::max and f64::min.