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.
#[derive(PartialEq, Eq, PartialOrd, Ord)] struct Version(u32, u32);
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
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
Ordfirst, thenPartialOrdasSome(self.cmp(other)). Writing both independently invites inconsistent results. - Consistency with
Eq:a.cmp(&b) == Equalmust matcha == b. Collections rely on it. - Floats:
f64is onlyPartialOrd, sosort()andmax()do not compile forVec<f64>. Usesort_by(|a, b| a.total_cmp(b))(NaN sorts to the ends) orpartial_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 instd::cmp::Reverse. ABinaryHeapis a max-heap;Reverseturns it into a min-heap. - Strings compare byte by byte (UTF-8 order), not by locale.
"Z" < "a"istrue. sort_by_keycalls the key function many times;sort_by_cached_keycomputes each key once when the key is expensive.clamp,max,minareOrdmethods;std::cmp::max/minare the free-function forms. For floats usef64::maxandf64::min.