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.
| Parameter | Description |
|---|---|
other | The 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.
#![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=LessRelated: slice sort and binary_search, integers page