Rust Reference ยท Standard Library Modules
Rust Ordering enum
Reference for std::cmp::Ordering (Less, Equal, Greater): cmp and partial_cmp, then and then_with, reverse, is_lt helpers, sort_by, plus atomic memory Ordering.
Rust has two unrelated types named Ordering. This page covers both, starting with the common one.
std::cmp::Ordering is the result of comparing two values. It is a three-variant enum: Less, Equal and Greater. The Ord::cmp method returns it, PartialOrd::partial_cmp returns Option<Ordering> (with None for incomparable values such as NaN), and sorting and searching functions such as sort_by, max_by and binary_search_by take closures that return one. std::sync::atomic::Ordering is a different enum that describes memory ordering for atomic operations and is covered at the end.
use std::cmp::Ordering; match 3.cmp(&5) { Ordering::Less => println!("smaller"), Ordering::Equal => println!("same"), Ordering::Greater => println!("bigger"), }
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 enum Ordering { Less = -1, Equal = 0, Greater = 1 } impl Ordering { pub const fn reverse(self) -> Ordering; pub const fn then(self, other: Ordering) -> Ordering; pub fn then_with<F: FnOnce() -> Ordering>(self, f: F) -> Ordering; pub const fn is_eq(self) -> bool; // also is_ne, is_lt, is_gt, is_le, is_ge } trait Ord: Eq + PartialOrd { fn cmp(&self, other: &Self) -> Ordering; } trait PartialOrd<Rhs = Self>: PartialEq<Rhs> { fn partial_cmp(&self, other: &Rhs) -> Option<Ordering>; }
| Name | Description |
|---|---|
reverse |
Swaps Less and Greater; Equal stays. Used to sort descending. |
then |
Returns self unless it is Equal, in which case it returns other. Both sides are always computed. |
then_with |
Same as then, but the closure runs only when self is Equal. Use it when the second comparison is costly. |
is_lt, is_le, is_gt, is_ge, is_eq, is_ne |
Convenience tests of the result. |
Returns. The variants are fixed at -1, 0 and 1, so ordering as i32 is safe, and Ord::cmp consistent with == is required for correct sorting.
Errors and panics. There are none in Ordering itself. A comparison function that does not form a total order may make sort_by panic or produce an unspecified (but memory-safe) order.
std::sync::atomic::Ordering
A separate enum with the variants Relaxed, Release, Acquire, AcqRel and SeqCst. It is passed to every atomic operation and states which memory effects other threads are guaranteed to see. Relaxed guarantees only the atomicity of that single operation; Release on a store paired with Acquire on a load makes everything written before the store visible after the load; AcqRel combines both for read-modify-write operations; SeqCst adds a single global order of all SeqCst operations. See atomics for examples.
Usage notes
- Same name, different module. Import with
use std::cmp::Ordering;for comparisons. When you need both in one file, import one by path (atomic::Ordering) or rename it withas. - Match must be exhaustive, which is why guessing games and binary searches use
match a.cmp(&b)with three arms. The compiler checks you covered all cases. - Lexicographic order is the default for strings, slices, tuples and
Vec: the first difference decides, and a shorter prefix sorts first. Structs that deriveOrdcompare fields in declaration order; enums compare by variant order first. - Floats implement only
PartialOrd.partial_cmpreturnsNonewhen aNaNis involved. Usef64::total_cmpfor sorting, or handleNoneexplicitly. sort_by_keyplusReverseis the shortest way to sort descending. Keys that borrow from the item needsort_byinstead (orsort_by_cached_keyfor expensive keys).- Consistency.
cmpmust agree withEq:a.cmp(&b) == Equalexactly whena == b. Violating this breaksBTreeMap,sortandbinary_search. Option<Ordering>can be compared too.Some(Less) < Some(Greater), andNonesorts before everySome.