Comparison Traits – Understanding Equality and Ordering in Rust

Rust’s equality rules ignite comment chaos — floats spark a NaN fight

TLDR: Rust explains why its rules make integers easy to sort but floats messy because NaN isn’t equal to itself. Comments erupted into a NaN fistfight: some want it “fixed,” others defend the standard, with everyone agreeing you must handle floats carefully when sorting or using them as keys.

Rust dropped a guide to how it decides what counts as equal and what can be sorted, and the comments turned into a full-on soap opera. The post explains the four traits that rule comparisons — PartialEq/Eq for equality and PartialOrd/Ord for ordering — and why floats (numbers with decimals) come with a notorious goblin called NaN (“Not a Number”) that refuses to play nice. The big takeaway: integers have simple, total ordering; floats do not, thanks to NaN being unequal to itself. Cue the drama.

The loudest reaction: frustration. One commenter fumed that NaN != NaN is “annoying,” and the thread quickly split into camps. Team “Make NaN equal to itself” wants fewer surprises in sorting and hash maps; Team “Math says no” clapped back, reminding everyone this is an IEEE standard, not a Rust quirk. There were jokes galore: “NaN is the gremlin in your cereal,” “Float sorting requires duct tape,” and “Hash maps with floats? Bring a fire extinguisher.”

Under the memes, practical tips landed: derive comparisons for your structs, use sort_by_key, flip order with Reverse, and chain tie-breakers with Ordering::then. The vibe: Rust is strict on purpose, floats are chaos goblins, and everyone has feelings about it. Drama served, lessons learned.

Key Points

  • Rust models equality and ordering with PartialEq/Eq and PartialOrd/Ord, alongside the Ordering enum.
  • Ord implies Eq and provides PartialOrd; Eq implies PartialEq, forming a hierarchy of guarantees.
  • Floats (e.g., f64) follow IEEE-754 semantics, making NaN unequal to itself and incomparable; thus f64 cannot implement Eq or Ord.
  • Eq requires reflexive, symmetric, transitive behavior; Ord requires total order and transitivity; PartialEq/PartialOrd allow incomparability.
  • Deriving comparison traits yields law-abiding implementations with lexicographic ordering for structs and declaration-based ordering for enums; practical tools include sort_by_key, std::cmp::Reverse, and Ordering::then/then_with.

Hottest takes

"I find floating point NaN != NaN quite annoying" — thomasmg
Made with <3 by @siedrix and @shesho from CDMX. Powered by Forge&Hive.