cmp

Ord, PartialOrd, Ordering, and Reverse, including why NaN is incomparable under PartialOrd and how total_cmp chooses a total order.

Ord is a total order: any two values compare as Less, Equal, or Greater. Integers implement Ord. PartialOrd is a weaker relation that may return None when two values are incomparable. Floating-point types implement PartialOrd and PartialEq, but they do not implement Ord, because IEEE NaN is incomparable with every value, including itself.

f64::total_cmp is an explicit total-order strategy over the IEEE 754 totalOrder. It is not the same relation as < or partial_cmp, and it does not make f64 implement Ord. Reverse wraps an ordered value and flips the order, which is how a max-heap becomes a min-heap on the VecDeque and BinaryHeap page. Examples were compiled with rustc 1.90.0 and --edition=2024.

Examples were compiled with rustc 1.90.0 using --edition=2024 and run as a plain binary. See the Rust 1.90.0 documentation for the complete API.

Rust reference overview →

API index

APISummary
Ord::cmp, PartialOrd::partial_cmp, f64::total_cmpCompare values that have a total order, or a partial order that can fail. total_cmp is a separate, explicit total order on floats.
std::cmp::ReverseWrap a value so that greater becomes less. Useful as a sort key or as a BinaryHeap element.

Ord, PartialOrd, NaN, and total_cmp

cmp always returns an Ordering. partial_cmp returns Option<Ordering>. For 1.5_f64 versus NaN, and for NaN versus NaN, partial_cmp is None. The == operator is also false for NaN == NaN. That is why a slice of f64 cannot call the Ord-bounded sort method; sort_by with total_cmp is the usual alternative.

On rustc 1.90.0, total_cmp follows IEEE totalOrder: -0.0 is less than 0.0, and a positive NaN compares greater than 0.0. Use total_cmp when you have chosen that total order. Do not pretend PartialOrd already provided one.

Ord::cmp, PartialOrd::partial_cmp, f64::total_cmp

pub trait Ord: Eq + PartialOrd {
    fn cmp(&self, other: &Self) -> Ordering;
}
pub trait PartialOrd: PartialEq {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering>;
}
pub const fn total_cmp(&self, other: &Self) -> Ordering
pub enum Ordering {
    Less = -1,
    Equal = 0,
    Greater = 1,
}

Compare values that have a total order, or a partial order that can fail. total_cmp is a separate, explicit total order on floats.

ParameterDescription
otherThe value on the right-hand side of the comparison.

Returns: cmp and total_cmp return Ordering. partial_cmp returns Some(Ordering) or None when the values are incomparable, including any comparison involving NaN.

  • The example compares NaN with == only to show the IEEE result false. Prefer is_nan when you are testing whether a value is NaN.
  • Integer overflow arithmetic stays on the integers page. This page is about ordering, not wrapping or checked arithmetic.
rust
#![allow(invalid_nan_comparisons)]

fn main() {
    println!("cmp={:?}", 1.cmp(&2));
    println!("partial={:?}", 2.partial_cmp(&1));
    println!("nan_vs_0={:?}", 1.5_f64.partial_cmp(&f64::NAN));
    println!("nan_vs_nan={:?}", f64::NAN.partial_cmp(&f64::NAN));
    println!("nan_eq={}", f64::NAN == f64::NAN);
    println!("total_nan_0={:?}", f64::NAN.total_cmp(&0.0));
    println!("total_0_nan={:?}", 0.0_f64.total_cmp(&f64::NAN));
    println!("total_neg0_0={:?}", (-0.0_f64).total_cmp(&0.0));
}

Expected output

cmp=Less
partial=Some(Greater)
nan_vs_0=None
nan_vs_nan=None
nan_eq=false
total_nan_0=Greater
total_0_nan=Less
total_neg0_0=Less

Related: slice sort and binary_search, integers page

Official documentation →

Reverse flips an order

std::cmp::Reverse is a wrapper that implements Ord and PartialOrd by swapping the direction of the inner comparison. sort_by_key with Reverse yields descending order. BinaryHeap is a max-heap, so Reverse turns it into a min-heap; that usage is on the VecDeque and BinaryHeap page rather than repeated here.

std::cmp::Reverse

pub struct Reverse<T>(pub T);

Wrap a value so that greater becomes less. Useful as a sort key or as a BinaryHeap element.

ParameterDescription
TThe inner ordered type. Reverse(T) implements Ord when T does.

Returns: Reverse is a value you store or pass as a key, not a comparison function of its own.

  • The tuple struct field is public, so Reverse(value) and a match or .0 access are both available.
rust
use std::cmp::Reverse;

fn main() {
    let mut values = vec![3, 1, 2];
    values.sort_by_key(|value| Reverse(*value));
    println!("reverse_sort={values:?}");
}

Expected output

reverse_sort=[3, 2, 1]

Related: BinaryHeap and Reverse as a min-heap, Official Reverse

Official documentation →