Skip to content

Commit 6f7222c

Browse files
authored
Rollup merge of #118714 - The-Ludwig:explain_ord_derive_enum_field, r=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.
2 parents a58ec8f + 5ec0a21 commit 6f7222c

File tree

1 file changed

+4
-2
lines changed

1 file changed

+4
-2
lines changed

library/core/src/cmp.rs

+4-2
Original file line numberDiff line numberDiff line change
@@ -710,7 +710,8 @@ impl<T: Clone> Clone for Reverse<T> {
710710
/// [lexicographic](https://en.wikipedia.org/wiki/Lexicographic_order) ordering
711711
/// based on the top-to-bottom declaration order of the struct's members.
712712
///
713-
/// When `derive`d on enums, variants are ordered by their discriminants.
713+
/// When `derive`d on enums, variants are ordered primarily by their discriminants.
714+
/// Secondarily, they are ordered by their fields.
714715
/// By default, the discriminant is smallest for variants at the top, and
715716
/// largest for variants at the bottom. Here's an example:
716717
///
@@ -963,7 +964,8 @@ pub macro Ord($item:item) {
963964
/// [lexicographic](https://en.wikipedia.org/wiki/Lexicographic_order) ordering
964965
/// based on the top-to-bottom declaration order of the struct's members.
965966
///
966-
/// When `derive`d on enums, variants are ordered by their discriminants.
967+
/// When `derive`d on enums, variants are primarily ordered by their discriminants.
968+
/// Secondarily, they are ordered by their fields.
967969
/// By default, the discriminant is smallest for variants at the top, and
968970
/// largest for variants at the bottom. Here's an example:
969971
///

0 commit comments

Comments
 (0)