Sub topic 10
Comparison operators: PartialEq and PartialOrd
This chapter assumes you know how to implement a trait, have seen the Add impl from earlier chapters, and understand borrowing. Comparison operators follow the same "operator is a method call" idea, with two differences. They live in std::cmp, not std::ops. They also take their operands by reference, so comparing never moves a value.
How comparisons map to traits
== and != come from PartialEq. <, <=, > and >= come from PartialOrd. The expression a == b is sugar for PartialEq::eq(&a, &b). The compiler inserts the borrows for you.
Because operands are borrowed, you can compare non-Copy types such as String and use a and b again afterwards.
Deriving versus implementing
For most types, #[derive(PartialEq)] is enough. It compares field by field. Write the impl by hand only when equality should differ from "every field matches", for example when comparing floating-point values with a tolerance.
PartialOrd has one required method, partial_cmp. It returns Option<Ordering>. The four operators have default methods built on it.
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!(!(Meters(f64::NAN) < Meters(1.0)));
assert!(!(Meters(f64::NAN) >= Meters(1.0)));
}The last two assertions show why the type is "partial". f64::NAN has no ordering relative to any number, so partial_cmp returns None. When that happens, all four operators return false.
Comparing against another type
Like Add, PartialEq has a Rhs parameter that defaults to Self. Setting it lets you compare two different types.
#[derive(Debug, PartialEq)]
struct Meters(f64);
impl PartialEq<f64> for Meters {
fn eq(&self, other: &f64) -> bool {
self.0 == *other
}
}
fn main() {
assert!(Meters(2.0) == 2.0);
assert!(Meters(2.0) == Meters(2.0));
assert!(Meters(2.0) != 3.0);
}PartialOrd<Rhs> works the same way, but it requires PartialEq<Rhs> to be implemented as well. Here != comes free, because ne defaults to !eq.
Partial versus total
Eq and Ord are marker-like upgrades. Eq promises that a == a always holds. Ord promises that every pair of values is comparable, through a cmp method that returns a plain Ordering. Floats cannot be Eq or Ord because of NaN. That is why f64 has no .sort(), and why you cannot use it as a BTreeMap key.
If your type does have a total order, implement Ord and have partial_cmp return Some(self.cmp(other)). This keeps the two consistent.
Derived ordering
#[derive(PartialOrd)] on a struct compares fields in declaration order, like a dictionary. On an enum, it compares variants by declaration order first, then by their contents. Reordering fields or variants therefore changes the behavior of <.
Exercise
What does Meters(f64::NAN) == Meters(f64::NAN) evaluate to when Meters derives PartialEq, and why can Meters not also derive Eq correctly?
Show answer
It evaluates to false, because the derived impl compares the inner f64 values and NaN is not equal to itself. Eq promises that a == a is always true, so a type holding an f64 that can be NaN would break that promise. (The compiler still accepts derive(Eq) only if every field is Eq, and f64 is not.)