In Rust, why can't a struct with f64 coordinate fields derive Eq, Ord or Hash, and how do you sort or key it?
answer
- one value unequal to itself
- partial versus total relations
- what partial_cmp returns for NaN
- total_cmp and to_bits
basics
~20 sBecause NaN != NaN, f64 implements only PartialEq and PartialOrd, never Eq, Ord or Hash, so deriving them on a struct with f64 fields fails with E0277. Sort with sort_by(f64::total_cmp); key through a wrapper or an integer encoding.
solid answer
~40 s`f64` follows IEEE 754, where `NaN != NaN`. That breaks reflexivity, so std gives floats `PartialEq` and `PartialOrd` only: `partial_cmp` returns `None` when either side is NaN. `Eq`, `Ord` and `Hash` are not implemented, so `#[derive(Eq, Hash)]` on a `Coord { lat: f64, lon: f64 }` fails with E0277, `vec_of_f64.sort()` fails because `f64: Ord` is not satisfied, and `HashSet<f64>::insert` is rejected for missing `Eq` and `Hash`. To sort, pass a comparator: `sort_by(f64::total_cmp)` (IEEE totalOrder, NaN placed by its sign) or `sort_by(|a, b| a.partial_cmp(b).unwrap())` when NaN is impossible. To key, store a fixed-point integer such as microdegrees in an `i64`, or wrap the floats in a newtype whose `Eq`, `Ord` and `Hash` all go through `total_cmp` and `to_bits`.
code
rust · 17 linesfn main() {
let mut readings = vec![12.5_f64, -3.0, f64::NAN, 0.0, 7.25];
// readings.sort(); // error[E0277]: the trait bound `f64: Ord` is not satisfied
// total_cmp is a total order; a positive NaN sorts after +infinity.
readings.sort_by(f64::total_cmp);
println!("{readings:?}");
// partial_cmp returns None for NaN, so unwrap() is only safe without NaN.
let mut clean = vec![12.5_f64, -3.0, 0.0, 7.25];
clean.sort_by(|a, b| a.partial_cmp(b).unwrap());
println!("{clean:?}");
println!("{:?}", f64::NAN.partial_cmp(&1.0));
println!("{}", f64::NAN == f64::NAN);
}go deeper
Recall that f64 has PartialEq and PartialOrd but not Eq, Ord or Hash, and that NaN != NaN is the reason. Know that v.sort() on floats does not compile.
Explain what each trait promises, why partial_cmp returns an Option, and show sort_by(f64::total_cmp). Name the E0277 bound each failing derive reports.
Choose a key representation for real data: fixed-point integers for coordinates, or a total_cmp newtype with matching Hash. Point out the -0.0 and NaN-payload consequences.
Frame it as a data-modelling decision: floating values rarely make good identities, so validate NaN at the boundary and pick an integer or newtype key type the whole codebase shares.
## The five traits and what each promises Rust splits comparison into separate traits in `core::cmp` and `core::hash`, and each one makes a different promise: | Trait | Method | Promise | |---|---|---| | `PartialEq` | `eq`, `ne` | symmetric and transitive equality; some values may equal nothing | | `Eq` | none to implement | adds **reflexivity**: `a == a` for every value | | `PartialOrd` | `partial_cmp` returns `Option<Ordering>` | some pairs may be **incomparable** (`None`) | | `Ord` | `cmp` returns `Ordering` | a **total order**: every pair compares | | `Hash` | `hash` | if `a == b` then `hash(a) == hash(b)` | `Eq` has no methods to implement. The compiler cannot check reflexivity, so `Eq` is a promise the author makes, and generic code such as `HashMap<K, V>`, `BTreeMap<K, V>` and `slice::sort` relies on it through its bounds. ## Why f64 stops at the partial traits IEEE 754 floating point defines NaN ("not a number") as unequal to everything, itself included. The standard library documents the consequence directly: floating point types implement `PartialEq` but not `Eq`, because `NaN != NaN`. - `f64::NAN == f64::NAN` is `false`, so reflexivity fails and `Eq` would be a lie. - `f64::NAN.partial_cmp(&1.0)` is `None`; both `NAN < 1.0` and `NAN > 1.0` are `false`. That rules out `Ord`, whose `cmp` must always answer. - `0.0 == -0.0` is `true` although the two have different bit patterns. A `Hash` that fed the raw bits to the hasher would give two equal values different hashes, which is one reason std does not implement `Hash` for floats at all. - Writing `x == f64::NAN` compiles but is always `false`; rustc warns with the `invalid_nan_comparisons` lint and `x.is_nan()` is the test you want. ## What rustc reports Each missing trait surfaces at the first place a bound needs it: 1. `#[derive(Eq)]` on a struct with an `f64` field: ``error[E0277]: the trait bound `f64: Eq` is not satisfied``, because the derive requires every field to be `Eq`. 2. `#[derive(Hash)]` on the same struct: ``error[E0277]: the trait bound `f64: Hash` is not satisfied``. 3. `v.sort()` on a `Vec<f64>`: ``error[E0277]: the trait bound `f64: Ord` is not satisfied``, raised from the `T: Ord` bound on `sort`. 4. `HashSet<f64>::insert`: `error[E0599]`, saying the method exists but its bounds `f64: Eq` and `f64: Hash` are not satisfied. Note what does compile: `#[derive(PartialEq, PartialOrd)]` on the struct is fine, because those derives only need the fields to be `PartialEq` and `PartialOrd`. ## Sorting floating-point data Sorting never needs `Ord` if you hand the sort a comparator. The choices, from most to least robust: 1. **`sort_by(f64::total_cmp)`** — `total_cmp` implements the IEEE 754 totalOrder predicate: negative NaN, negative infinity, negatives, `-0.0`, `+0.0`, positives, positive infinity, positive NaN. It is a genuine total order, so the sort is well defined even with NaN present. It does treat `-0.0` as less than `+0.0`, unlike `==`. 2. **`sort_by(|a, b| a.partial_cmp(b).unwrap())`** — fine when NaN cannot occur; the slice docs suggest it for values known to be in a totally ordered subset. A NaN makes it panic with "called `Option::unwrap()` on a `None` value". 3. **Filter or reject NaN at the boundary**, then use option 2. For coordinate data a NaN is usually a parsing bug, so refusing it early is often the right fix. Mapping `None` to `Ordering::Equal` looks like a fourth option but is not a total order: it makes every number "equal" to NaN, breaking transitivity, and the sort is allowed to return garbage or panic. ## Using coordinates as keys A `HashSet` or `HashMap` key needs `Eq + Hash`; a `BTreeMap` key needs `Ord`. For a geographic coordinate the usual options are: - **Fixed-point integers.** Store latitude and longitude as `i64` microdegrees (or `i32` at lower precision). Integers derive `Eq`, `Ord` and `Hash` with no caveats, and equality now means "same grid cell", which is usually what the domain wants. - **A newtype with a deliberate total order.** Implement `Ord` with `total_cmp`, derive `PartialOrd` from it as `Some(self.cmp(other))`, define `eq` as `cmp(..) == Equal`, and hash `to_bits()`. Under `total_cmp`, two floats compare `Equal` exactly when their bits match, so this `Hash` agrees with this `Eq`. The price: `-0.0` and `+0.0` become different keys, and each distinct NaN payload is its own key. - **Hashing `to_bits()` beside the built-in `==`** is the version that goes wrong: `0.0 == -0.0` holds while their bits differ, so the `Hash` contract is broken. The rule underneath all three: whatever you choose, equality, ordering and hashing must describe the same relation.
- Why does #[derive(PartialEq, PartialOrd)] compile on a struct with f64 fields when Eq and Ord do not?Those derives only need each field to implement `PartialEq` and `PartialOrd`, which `f64` does. The generated `partial_cmp` compares fields in declaration order and returns `None` when the first non-equal field comparison is `None`, so a coordinate whose `lat` is NaN is neither less than, greater than nor equal to any coordinate, itself included.
- Is sort_by(|a, b| a.partial_cmp(b).unwrap()) acceptable in production code?Only where NaN is impossible by construction, for example values validated with `is_finite` at the input boundary. Otherwise a single NaN panics the sort with the `Option::unwrap()` message. `sort_by(f64::total_cmp)` costs about the same and never panics, so it is the safer default.
- Why is hashing to_bits() consistent in the total_cmp newtype but not beside f64's own ==?`total_cmp` returns `Equal` only when the two bit patterns are identical, so equal values always hash alike. The built-in `==` says `0.0 == -0.0` although their bits differ, so a bit-based `Hash` would give two equal values different hashes and break the `Hash` contract.
- f64 cannot be a HashMap key because hashing floats is too slow.
- Deriving Eq on an f64 struct works because PartialEq is derived first.
- f64 implements Ord, but its cmp panics when it meets NaN.
- Comparing x == f64::NAN is the right way to detect a missing reading.
- Hashing to_bits() is always consistent with f64's built-in ==.
- Mapping partial_cmp's None to Ordering::Equal makes float sorting safe.