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.
This commit is contained in:
commit
6f7222c1e6
@ -710,7 +710,8 @@ fn clone_from(&mut self, other: &Self) {
|
||||
/// [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:
|
||||
///
|
||||
@ -963,7 +964,8 @@ fn clamp(self, min: Self, max: Self) -> Self
|
||||
/// [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:
|
||||
///
|
||||
|
Loading…
Reference in New Issue
Block a user