Skip to content

Commit

Permalink
Rollup merge of #118714 - The-Ludwig:explain_ord_derive_enum_field, r…
Browse files Browse the repository at this point in the history
…=Nilstrieb

 Explanation that fields are being used when deriving `(Partial)Ord` on enums

When deriving `std::cmp::Ord` or `std::cmp::PartialOrd` on enums, their fields are compared if the variants are equal.
This means that the last assertion in the following snipped panics.
```rust
use std::cmp::{PartialEq, Eq, PartialOrd, Ord};

#[derive(PartialEq, Eq, PartialOrd, Ord)]
enum Sizes {
    Small(usize),
    Big(usize),
}

fn main() {
    let a = Sizes::Big(3);
    let b = Sizes::Big(5);
    let c = Sizes::Small(10);
    assert!( c < a);
    assert_eq!(a, c);
}
```

This is more often expected behavior than not, and can be easily circumvented, as discussed in [this thread](https://users.rust-lang.org/t/how-to-sort-enum-variants/52291/4).
But it is addressed nowhere in the documentation, yet.
So I stumbled across this, as I personally did not expect fields being used in `PartialOrd`.
I added the explanation to the documentation.
  • Loading branch information
matthiaskrgr committed Jan 22, 2024
2 parents a58ec8f + 5ec0a21 commit 6f7222c
Showing 1 changed file with 4 additions and 2 deletions.
6 changes: 4 additions & 2 deletions library/core/src/cmp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -710,7 +710,8 @@ impl<T: Clone> Clone for Reverse<T> {
/// [lexicographic](https://en.wikipedia.org/wiki/Lexicographic_order) ordering
/// based on the top-to-bottom declaration order of the struct's members.
///
/// When `derive`d on enums, variants are ordered by their discriminants.
/// When `derive`d on enums, variants are ordered primarily by their discriminants.
/// Secondarily, they are ordered by their fields.
/// By default, the discriminant is smallest for variants at the top, and
/// largest for variants at the bottom. Here's an example:
///
Expand Down Expand Up @@ -963,7 +964,8 @@ pub macro Ord($item:item) {
/// [lexicographic](https://en.wikipedia.org/wiki/Lexicographic_order) ordering
/// based on the top-to-bottom declaration order of the struct's members.
///
/// When `derive`d on enums, variants are ordered by their discriminants.
/// When `derive`d on enums, variants are primarily ordered by their discriminants.
/// Secondarily, they are ordered by their fields.
/// By default, the discriminant is smallest for variants at the top, and
/// largest for variants at the bottom. Here's an example:
///
Expand Down

0 comments on commit 6f7222c

Please sign in to comment.