]> git.lizzy.rs Git - rust.git/commitdiff
Add an example for deriving PartialOrd on enums
authorAriel Davis <ariel.z.davis@icloud.com>
Sat, 21 Aug 2021 02:24:22 +0000 (22:24 -0400)
committerAriel Davis <ariel.z.davis@icloud.com>
Sat, 21 Aug 2021 02:24:22 +0000 (22:24 -0400)
For some reason, I always forget which variants are smaller and which
are larger when you derive PartialOrd on an enum. And the wording in the
current docs is not entirely clear to me.

So, I often end up making a small enum, deriving PartialOrd on it, and
then writing a `#[test]` with an assert that the top one is smaller than
the bottom one (or the other way around) to figure out which way the
deriving goes.

So then I figured, it would be great if the standard library docs just
had that example, so if I keep forgetting, at least I can figure it out
quickly by looking at std's docs.

library/core/src/cmp.rs

index 79610bb409d37c06b383ea7622452560b179ebf6..4e82b65539460eeaffeb71fe8839a79c93359548 100644 (file)
@@ -660,6 +660,18 @@ fn clone_from(&mut self, other: &Self) {
 /// This trait can be used with `#[derive]`. When `derive`d on structs, it will produce a
 /// [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 top-to-bottom discriminant order.
+/// This means variants at the top are less than variants at the bottom.
+/// Here's an example:
+///
+/// ```
+/// #[derive(PartialEq, PartialOrd)]
+/// enum Size {
+///     Small,
+///     Large,
+/// }
+///
+/// assert!(Size::Small < Size::Large);
+/// ```
 ///
 /// ## Lexicographical comparison
 ///