Sub topic 10
Comparison Operators: PartialEq and PartialOrd
This chapter assumes you know how to implement a trait for your own type, how derive works, and how Option and match work. It also assumes you have seen the std::ops traits such as Add. Comparison operators look like the arithmetic ones, but they differ in three ways: they live in std::cmp, they take operands by reference, and they return bool.
Comparisons are traits too
The operators ==, !=, <, <=, > and >= are sugar for trait method calls, just like +. They are not in std::ops. They belong to two traits in std::cmp.
| Expression | Method call | Trait |
|---|---|---|
| `a == b` | `PartialEq::eq(&a, &b)` | `PartialEq` |
| `a != b` | `PartialEq::ne(&a, &b)` | `PartialEq` |
| `a < b` | `PartialOrd::lt(&a, &b)` | `PartialOrd` |
| `a <= b` | `PartialOrd::le(&a, &b)` | `PartialOrd` |
| `a > b` | `PartialOrd::gt(&a, &b)` | `PartialOrd` |
| `a >= b` | `PartialOrd::ge(&a, &b)` | `PartialOrd` |
Every method takes &self and &other. The compiler inserts the borrows for you, so a == b never moves or consumes a or b. This is the main difference from Add. A non-Copy type can be compared as many times as you like without Clone and without reference impls.
PartialEq: equality
PartialEq has one required method, eq. The method ne has a default body that returns !self.eq(other). You rarely override it.
For most types, deriving is the right choice. The derived impl compares every field with ==, in declaration order.
#[derive(Debug, Clone, Copy, PartialEq)]
struct Meters(f64);
fn main() {
assert!(Meters(1.5) == Meters(1.5));
assert!(Meters(1.5) != Meters(2.5));
}Comparing different types
PartialEq has a type parameter, PartialEq<Rhs = Self>. It plays the same role as Rhs in Add. Implementing it for another type lets you compare across types.
use std::cmp::Ordering;
#[derive(Debug, Clone, Copy, PartialEq)]
struct Meters(f64);
impl PartialEq<f64> for Meters {
fn eq(&self, other: &f64) -> bool {
self.0 == *other
}
}
impl PartialOrd<f64> for Meters {
fn partial_cmp(&self, other: &f64) -> Option<Ordering> {
self.0.partial_cmp(other)
}
}
fn main() {
assert!(Meters(2.0) == 2.0_f64);
assert!(Meters(2.0) < 3.0_f64);
assert!(Meters(2.0) != 5.0_f64);
}The impl is one-directional. Meters == f64 compiles, but f64 == Meters does not. For that you would need impl PartialEq<Meters> for f64. The orphan rule allows it because Meters is a local type argument, as with Mul<Vec2> for f64 in the previous chapters.
References add a restriction. The standard library implements PartialEq<&B> for &A when A: PartialEq<B>. So &a == &b works, but &a == b does not compile. The compiler reports a type mismatch, and the fix is to dereference one side.
PartialOrd: ordering
PartialOrd requires PartialEq as a supertrait. Its one required method is partial_cmp, which returns Option<Ordering>. The four operators <, <=, > and >= have default bodies built on partial_cmp. Implement partial_cmp and you get all four.
use std::cmp::Ordering;
#[derive(Debug, PartialEq)]
struct Meters(f64);
impl PartialOrd for Meters {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
self.0.partial_cmp(&other.0)
}
}
fn main() {
assert!(Meters(1.0) < Meters(2.0));
assert!(Meters(3.0) >= Meters(3.0));
assert_eq!(Meters(1.0).partial_cmp(&Meters(2.0)), Some(Ordering::Less));
}Why the result is an Option
"Partial" means that some pairs of values have no defined order. The standard example is f64::NAN. It is neither less than, equal to, nor greater than any value, including itself. partial_cmp returns None for such pairs, and all four operators return false.
fn main() {
let nan = f64::NAN;
assert_eq!(nan.partial_cmp(&1.0), None);
assert!(!(nan < 1.0));
assert!(!(nan >= 1.0));
assert!(nan != nan);
}A common mistake follows from this. !(a < b) is not the same as a >= b when either value might be unordered. Do not rewrite one into the other for types that wrap floats.
Derived ordering
Deriving PartialOrd compares structs field by field in declaration order, which is lexicographic comparison. For enums, a later variant is greater than an earlier one, and variants with data compare their fields when the variants match.
#[derive(Debug, PartialEq, PartialOrd)]
struct Version {
major: u32,
minor: u32,
}
#[derive(Debug, PartialEq, PartialOrd)]
enum Level {
Low,
High,
}
fn main() {
assert!(Version { major: 1, minor: 9 } < Version { major: 2, minor: 0 });
assert!(Level::Low < Level::High);
}Field order is part of your behavior. Reordering the fields of a struct that derives PartialOrd changes how it sorts, with no compile error. Put the most significant field first.
The consistency rules
The compiler cannot check the following rules. Violating them leads to wrong results in sorted collections and in code that assumes they hold.
a == bmust be symmetric (b == a) and transitive.partial_cmpmust agree with==. In other words,a.partial_cmp(&b) == Some(Ordering::Equal)exactly whena == b.a < bmust be the opposite ofb > a.
If you implement both traits by hand, make partial_cmp the source of truth, or derive both so they cannot drift apart.
From partial to total: Eq and Ord
Two marker-style traits add stronger guarantees on top of the partial ones.
Eqhas no methods. It promises thata == ais always true.f64does not implement it because ofNaN.Ordaddscmp, which returns a plainOrdering. It promises that every pair of values is comparable.Ordrequires bothEqandPartialOrd.
You need Ord to use a type as a BTreeMap key, to call .sort() on a Vec of it, or to put it in a BinaryHeap. A type that only implements PartialOrd can be sorted with sort_by and a closure, but not with sort.
To order a float wrapper totally, use f64::total_cmp. It defines an order that places negative zero before positive zero and puts NaN after every other value. The PartialEq impl must use the same order, or rule 2 breaks.
use std::cmp::Ordering;
#[derive(Debug, Clone, Copy)]
struct Score(f64);
impl PartialEq for Score {
fn eq(&self, other: &Self) -> bool {
self.cmp(other) == Ordering::Equal
}
}
impl Eq for Score {}
impl PartialOrd for Score {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Score {
fn cmp(&self, other: &Self) -> Ordering {
self.0.total_cmp(&other.0)
}
}
fn main() {
let mut v = vec![Score(2.0), Score(f64::NAN), Score(-1.0)];
v.sort();
assert_eq!(v[0], Score(-1.0));
assert_eq!(v[1], Score(2.0));
assert!(v[2].0.is_nan());
assert_eq!(Score(f64::NAN), Score(f64::NAN));
assert!(Score(-0.0) < Score(0.0));
}The last two assertions show the cost of this choice. Score(NaN) equals itself, and -0.0 is less than 0.0, which differs from plain f64 behavior. Decide whether your domain accepts that. Often the better design rejects NaN in a constructor, so a plain derived order is enough.
Here partial_cmp delegates to cmp, which is the recommended pattern when Ord exists. The reverse, with cmp calling partial_cmp(...).unwrap(), risks a panic.
Common errors
- Deriving
Eqon a float wrapper.#[derive(Eq)]on a struct with anf64field fails to compile, becausef64is notEq. - Mixed derives. Deriving
PartialOrdwhile writingPartialEqby hand, or the reverse, can break rule 2. Derive both together unless you have a reason not to. - Expecting
&a == bto work. Both sides must have the same reference level, unless you add an explicit impl. - Comparing
Option<T>values with<. This works whenT: PartialOrd, andNoneis less than anySome. That may not be the ordering you want.
Exercise
A struct Reading(f64) derives PartialEq and implements PartialOrd with self.0.partial_cmp(&other.0). For a = Reading(f64::NAN) and b = Reading(1.0), what do a < b, a >= b and a.partial_cmp(&b) return? Can you call .sort() on a Vec<Reading>, and what would you need to change to allow it?
Show answer
a < b is false, a >= b is false, and a.partial_cmp(&b) is None, because NaN is unordered against every value. .sort() does not compile, because it needs Ord, and Reading implements neither Eq nor Ord. To allow it, either use sort_by(|x, y| x.0.total_cmp(&y.0)), or implement Eq and Ord using total_cmp and make PartialEq and PartialOrd agree with that order, as Score does above.