In Rust, how does #[derive(PartialOrd, Ord)] order struct values and enum variants, and why can reordering struct fields change sort results?
answer
- dictionary order
- top-to-bottom declaration
- discriminant before fields
- a refactor that re-sorts
basics
~20 sThe derive compares struct fields lexicographically in top-to-bottom declaration order, and enum values by discriminant first (the top variant is smallest by default), then by fields. Moving a field changes which comparison runs first, so sort order silently changes.
solid answer
~40 sDerived `PartialOrd` and `Ord` produce a lexicographic ordering: compare the first declared field, and only if it is equal move to the next. For `struct Player { score: u32, name: String }` that means score first, name as tie-breaker. On enums, values are ordered primarily by discriminant and secondarily by the variant's fields; by default the discriminant grows from the top variant down, but explicit discriminants such as `Low = 10, High = 1` override that. Because the order lives in the declaration, swapping two fields in a struct definition compiles cleanly and changes every `sort`, `max` and ordered-map iteration that uses the type. When the order is a business rule, write `Ord` by hand or sort with an explicit comparator.
code
rust · 16 lines#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
enum Tier { Gold, Silver, Bronze }
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
struct Player { score: u32, name: String, tier: Tier }
fn main() {
println!("{}", Tier::Gold < Tier::Bronze);
let a = Player { score: 90, name: "zoe".into(), tier: Tier::Bronze };
let b = Player { score: 90, name: "amy".into(), tier: Tier::Gold };
let c = Player { score: 120, name: "bob".into(), tier: Tier::Silver };
let mut v = vec![c, a, b];
v.sort();
for p in &v { println!("{} {} {:?}", p.score, p.name, p.tier); }
println!("{:?}", v.iter().max().map(|p| &p.name));
}go deeper
Recall that derived ordering compares fields from the top of the struct down and enum variants from the top variant down.
Explain lexicographic comparison, the discriminant rule for enums including explicit discriminants, and which traits each derive needs on fields.
Flag field reordering as a behaviour change in review, and move business orderings into a hand-written Ord or explicit comparators.
Decide which types may rely on derived order and require a comment or test pinning the order on any type that is sorted or used as an ordered key.
## Lexicographic order over declared fields When you write `#[derive(PartialEq, Eq, PartialOrd, Ord)]` on a struct, the generated `cmp` follows the rule documented on `Ord`: a **lexicographic** ordering based on the **top-to-bottom declaration order** of the struct's members. It behaves like comparing words in a dictionary: 1. Compare the first field. If it differs, that result is the answer. 2. If it is `Equal`, compare the second field, and so on. 3. If every field is `Equal`, the values are `Equal`. For a leaderboard type ```rust #[derive(PartialEq, Eq, PartialOrd, Ord)] struct Player { score: u32, name: String, tier: Tier } ``` the derived order is "lower score first; among equal scores, alphabetical name; among equal names, by tier". Derived `PartialOrd` does the same with `partial_cmp`, returning `None` the moment a field comparison is `None` (an `f64` field holding NaN, for instance). ## Enum order: discriminant first, then fields For enums the core docs state the rule precisely: variants are ordered **primarily by their discriminants**, **secondarily by their fields**. By default the discriminant is smallest for the top variant and largest for the bottom one, so the familiar shorthand "earlier variants are smaller" (the Rust Book's phrasing) holds only while you leave discriminants alone. - `enum Tier { Gold, Silver, Bronze }` derives `Gold < Silver < Bronze`. If you meant "Gold is best", that ordering reads backwards for a "max" query. - `enum Priority { Low = 10, High = 1 }` derives `High < Low`, because explicit discriminants override the declaration order. rustc 1.99.1 confirms `Priority::High < Priority::Low` is `true`. - Two values of the **same** variant compare by that variant's fields, again in declaration order: `Purchase(3) < Purchase(7)`. - Data-carrying variants still compare by variant first: any `Login { .. }` is less than any `Purchase(..)` when `Login` is declared first, whatever their payloads. ## Why moving a field changes behaviour The ordering is a function of source layout, which makes it fragile: - A tidy-up that sorts struct fields alphabetically, moves `name` above `score`, or inserts a new field at the top compiles without a warning, and every `sort`, `sort_unstable`, `iter().max()`, `BinaryHeap` and ordered-map key using the derived `Ord` now behaves differently. - Adding a field changes the tie-breaking even if it is appended at the end, since values that used to be equal may now differ. - Reordering enum variants changes their default discriminants and therefore their order, which also changes the integer you get from an `as` cast on a field-less enum. Derived `PartialEq` and `Eq` give the same answers whatever the field order, so the ordering derives are the ones whose results move. Tests that only check "the list is sorted" will keep passing; tests that pin an expected order will catch it. ## Requirements of the derives | Derive | Requires on the type | Requires on every field | |---|---|---| | `PartialOrd` | `PartialEq` | `PartialOrd` | | `Ord` | `Eq` and `PartialOrd` | `Ord` | On a generic type the derive adds a bound per type parameter, so `#[derive(PartialOrd)] struct Ranked<T>` is comparable only where `T: PartialOrd`. The docs advise that if you derive `Ord` you should derive all four (`PartialEq`, `Eq`, `PartialOrd`, `Ord`), so they agree by construction. Mixing a hand-written `PartialEq` with derived `Ord` is how types end up claiming two values are `Equal` under `cmp` but unequal under `==`. ## When to stop deriving Derive `Ord` when declaration order genuinely is the natural order: version tuples, `(major, minor, patch)` structs, field-less enums whose declaration order is the meaning. Write it by hand, or keep it out of the type and sort with a comparator, when: 1. The order is a business rule, such as "highest score first, then name", which is descending on one field. 2. Some fields must be ignored, such as a cached display string or a timestamp. 3. More than one ordering is needed in different places; a type has one `Ord`, so the others belong in `sort_by` closures. A useful habit is a short comment on the derive line, such as `// Ord: score, then name — field order matters`, so the next person who reorders fields knows they are changing behaviour.
- How would you make the derived order put the highest score first without writing Ord by hand?Wrap the field: declare `score: std::cmp::Reverse<u32>` so the derive compares it backwards. It works, but it leaks a sorting concern into the data type and every reader must unwrap `.0`. A `sort_by` comparator or a hand-written `Ord` usually reads better.
- Does derived PartialOrd on an enum ever look at the fields of different variants?No. Values of different variants are decided by their discriminants alone; fields are compared only when both values are the same variant. That is why every `Login { .. }` sorts before every `Purchase(..)` when `Login` is declared first.
- The derived Ord compares struct fields in alphabetical order of their names.
- Derived enum ordering always follows declaration order, even with explicit discriminants.
- Reordering struct fields is purely cosmetic and cannot change behaviour.
- Derived Ord on a struct compares the fields that differ most first.
- You can derive Ord on a struct whose fields only implement PartialOrd.