1 //! Functionality for ordering and comparison.
3 //! This module contains various tools for ordering and comparing values. In
6 //! * [`Eq`] and [`PartialEq`] are traits that allow you to define total and
7 //! partial equality between values, respectively. Implementing them overloads
8 //! the `==` and `!=` operators.
9 //! * [`Ord`] and [`PartialOrd`] are traits that allow you to define total and
10 //! partial orderings between values, respectively. Implementing them overloads
11 //! the `<`, `<=`, `>`, and `>=` operators.
12 //! * [`Ordering`] is an enum returned by the main functions of [`Ord`] and
13 //! [`PartialOrd`], and describes an ordering.
14 //! * [`Reverse`] is a struct that allows you to easily reverse an ordering.
15 //! * [`max`] and [`min`] are functions that build off of [`Ord`] and allow you
16 //! to find the maximum or minimum of two values.
18 //! For more details, see the respective documentation of each item in the list.
23 #![stable(feature = "rust1", since = "1.0.0")]
25 use self::Ordering::*;
27 /// Trait for equality comparisons which are [partial equivalence
28 /// relations](https://en.wikipedia.org/wiki/Partial_equivalence_relation).
30 /// `x.eq(y)` can also be written `x == y`, and `x.ne(y)` can be written `x != y`.
31 /// We use the easier-to-read infix notation in the remainder of this documentation.
33 /// This trait allows for partial equality, for types that do not have a full
34 /// equivalence relation. For example, in floating point numbers `NaN != NaN`,
35 /// so floating point types implement `PartialEq` but not [`trait@Eq`].
37 /// Implementations must ensure that `eq` and `ne` are consistent with each other:
39 /// - `a != b` if and only if `!(a == b)`
40 /// (ensured by the default implementation).
42 /// If [`PartialOrd`] or [`Ord`] are also implemented for `Self` and `Rhs`, their methods must also
43 /// be consistent with `PartialEq` (see the documentation of those traits for the exact
44 /// requirements). It's easy to accidentally make them disagree by deriving some of the traits and
45 /// manually implementing others.
47 /// The equality relation `==` must satisfy the following conditions
48 /// (for all `a`, `b`, `c` of type `A`, `B`, `C`):
50 /// - **Symmetric**: if `A: PartialEq<B>` and `B: PartialEq<A>`, then **`a == b`
51 /// implies `b == a`**; and
53 /// - **Transitive**: if `A: PartialEq<B>` and `B: PartialEq<C>` and `A:
54 /// PartialEq<C>`, then **`a == b` and `b == c` implies `a == c`**.
56 /// Note that the `B: PartialEq<A>` (symmetric) and `A: PartialEq<C>`
57 /// (transitive) impls are not forced to exist, but these requirements apply
58 /// whenever they do exist.
62 /// This trait can be used with `#[derive]`. When `derive`d on structs, two
63 /// instances are equal if all fields are equal, and not equal if any fields
64 /// are not equal. When `derive`d on enums, each variant is equal to itself
65 /// and not equal to the other variants.
67 /// ## How can I implement `PartialEq`?
69 /// An example implementation for a domain in which two books are considered
70 /// the same book if their ISBN matches, even if the formats differ:
81 /// format: BookFormat,
84 /// impl PartialEq for Book {
85 /// fn eq(&self, other: &Self) -> bool {
86 /// self.isbn == other.isbn
90 /// let b1 = Book { isbn: 3, format: BookFormat::Paperback };
91 /// let b2 = Book { isbn: 3, format: BookFormat::Ebook };
92 /// let b3 = Book { isbn: 10, format: BookFormat::Paperback };
94 /// assert!(b1 == b2);
95 /// assert!(b1 != b3);
98 /// ## How can I compare two different types?
100 /// The type you can compare with is controlled by `PartialEq`'s type parameter.
101 /// For example, let's tweak our previous code a bit:
104 /// // The derive implements <BookFormat> == <BookFormat> comparisons
105 /// #[derive(PartialEq)]
106 /// enum BookFormat {
114 /// format: BookFormat,
117 /// // Implement <Book> == <BookFormat> comparisons
118 /// impl PartialEq<BookFormat> for Book {
119 /// fn eq(&self, other: &BookFormat) -> bool {
120 /// self.format == *other
124 /// // Implement <BookFormat> == <Book> comparisons
125 /// impl PartialEq<Book> for BookFormat {
126 /// fn eq(&self, other: &Book) -> bool {
127 /// *self == other.format
131 /// let b1 = Book { isbn: 3, format: BookFormat::Paperback };
133 /// assert!(b1 == BookFormat::Paperback);
134 /// assert!(BookFormat::Ebook != b1);
137 /// By changing `impl PartialEq for Book` to `impl PartialEq<BookFormat> for Book`,
138 /// we allow `BookFormat`s to be compared with `Book`s.
140 /// A comparison like the one above, which ignores some fields of the struct,
141 /// can be dangerous. It can easily lead to an unintended violation of the
142 /// requirements for a partial equivalence relation. For example, if we kept
143 /// the above implementation of `PartialEq<Book>` for `BookFormat` and added an
144 /// implementation of `PartialEq<Book>` for `Book` (either via a `#[derive]` or
145 /// via the manual implementation from the first example) then the result would
146 /// violate transitivity:
149 /// #[derive(PartialEq)]
150 /// enum BookFormat {
156 /// #[derive(PartialEq)]
159 /// format: BookFormat,
162 /// impl PartialEq<BookFormat> for Book {
163 /// fn eq(&self, other: &BookFormat) -> bool {
164 /// self.format == *other
168 /// impl PartialEq<Book> for BookFormat {
169 /// fn eq(&self, other: &Book) -> bool {
170 /// *self == other.format
175 /// let b1 = Book { isbn: 1, format: BookFormat::Paperback };
176 /// let b2 = Book { isbn: 2, format: BookFormat::Paperback };
178 /// assert!(b1 == BookFormat::Paperback);
179 /// assert!(BookFormat::Paperback == b2);
181 /// // The following should hold by transitivity but doesn't.
182 /// assert!(b1 == b2); // <-- PANICS
192 /// assert_eq!(x == y, false);
193 /// assert_eq!(x.eq(&y), false);
196 /// [`eq`]: PartialEq::eq
197 /// [`ne`]: PartialEq::ne
199 #[stable(feature = "rust1", since = "1.0.0")]
202 #[rustc_on_unimplemented(
203 message = "can't compare `{Self}` with `{Rhs}`",
204 label = "no implementation for `{Self} == {Rhs}`"
206 pub trait PartialEq<Rhs: ?Sized = Self> {
207 /// This method tests for `self` and `other` values to be equal, and is used
210 #[stable(feature = "rust1", since = "1.0.0")]
211 fn eq(&self, other: &Rhs) -> bool;
213 /// This method tests for `!=`.
216 #[stable(feature = "rust1", since = "1.0.0")]
217 fn ne(&self, other: &Rhs) -> bool {
222 /// Derive macro generating an impl of the trait `PartialEq`.
223 #[rustc_builtin_macro]
224 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
225 #[allow_internal_unstable(core_intrinsics, structural_match)]
226 pub macro PartialEq($item:item) {
227 /* compiler built-in */
230 /// Trait for equality comparisons which are [equivalence relations](
231 /// https://en.wikipedia.org/wiki/Equivalence_relation).
233 /// This means, that in addition to `a == b` and `a != b` being strict inverses, the equality must
234 /// be (for all `a`, `b` and `c`):
236 /// - reflexive: `a == a`;
237 /// - symmetric: `a == b` implies `b == a`; and
238 /// - transitive: `a == b` and `b == c` implies `a == c`.
240 /// This property cannot be checked by the compiler, and therefore `Eq` implies
241 /// [`PartialEq`], and has no extra methods.
245 /// This trait can be used with `#[derive]`. When `derive`d, because `Eq` has
246 /// no extra methods, it is only informing the compiler that this is an
247 /// equivalence relation rather than a partial equivalence relation. Note that
248 /// the `derive` strategy requires all fields are `Eq`, which isn't
251 /// ## How can I implement `Eq`?
253 /// If you cannot use the `derive` strategy, specify that your type implements
254 /// `Eq`, which has no methods:
257 /// enum BookFormat { Paperback, Hardback, Ebook }
260 /// format: BookFormat,
262 /// impl PartialEq for Book {
263 /// fn eq(&self, other: &Self) -> bool {
264 /// self.isbn == other.isbn
267 /// impl Eq for Book {}
271 #[stable(feature = "rust1", since = "1.0.0")]
272 pub trait Eq: PartialEq<Self> {
273 // this method is used solely by #[deriving] to assert
274 // that every component of a type implements #[deriving]
275 // itself, the current deriving infrastructure means doing this
276 // assertion without using a method on this trait is nearly
279 // This should never be implemented by hand.
281 #[no_coverage] // rust-lang/rust#84605
283 #[stable(feature = "rust1", since = "1.0.0")]
284 fn assert_receiver_is_total_eq(&self) {}
287 /// Derive macro generating an impl of the trait `Eq`.
288 #[rustc_builtin_macro]
289 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
290 #[allow_internal_unstable(core_intrinsics, derive_eq, structural_match, no_coverage)]
291 pub macro Eq($item:item) {
292 /* compiler built-in */
295 // FIXME: this struct is used solely by #[derive] to
296 // assert that every component of a type implements Eq.
298 // This struct should never appear in user code.
300 #[allow(missing_debug_implementations)]
301 #[unstable(feature = "derive_eq", reason = "deriving hack, should not be public", issue = "none")]
302 pub struct AssertParamIsEq<T: Eq + ?Sized> {
303 _field: crate::marker::PhantomData<T>,
306 /// An `Ordering` is the result of a comparison between two values.
311 /// use std::cmp::Ordering;
313 /// let result = 1.cmp(&2);
314 /// assert_eq!(Ordering::Less, result);
316 /// let result = 1.cmp(&1);
317 /// assert_eq!(Ordering::Equal, result);
319 /// let result = 2.cmp(&1);
320 /// assert_eq!(Ordering::Greater, result);
322 #[derive(Clone, Copy, PartialEq, Debug, Hash)]
323 #[stable(feature = "rust1", since = "1.0.0")]
325 /// An ordering where a compared value is less than another.
326 #[stable(feature = "rust1", since = "1.0.0")]
328 /// An ordering where a compared value is equal to another.
329 #[stable(feature = "rust1", since = "1.0.0")]
331 /// An ordering where a compared value is greater than another.
332 #[stable(feature = "rust1", since = "1.0.0")]
337 /// Returns `true` if the ordering is the `Equal` variant.
342 /// use std::cmp::Ordering;
344 /// assert_eq!(Ordering::Less.is_eq(), false);
345 /// assert_eq!(Ordering::Equal.is_eq(), true);
346 /// assert_eq!(Ordering::Greater.is_eq(), false);
350 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
351 #[stable(feature = "ordering_helpers", since = "1.53.0")]
352 pub const fn is_eq(self) -> bool {
353 matches!(self, Equal)
356 /// Returns `true` if the ordering is not the `Equal` variant.
361 /// use std::cmp::Ordering;
363 /// assert_eq!(Ordering::Less.is_ne(), true);
364 /// assert_eq!(Ordering::Equal.is_ne(), false);
365 /// assert_eq!(Ordering::Greater.is_ne(), true);
369 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
370 #[stable(feature = "ordering_helpers", since = "1.53.0")]
371 pub const fn is_ne(self) -> bool {
372 !matches!(self, Equal)
375 /// Returns `true` if the ordering is the `Less` variant.
380 /// use std::cmp::Ordering;
382 /// assert_eq!(Ordering::Less.is_lt(), true);
383 /// assert_eq!(Ordering::Equal.is_lt(), false);
384 /// assert_eq!(Ordering::Greater.is_lt(), false);
388 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
389 #[stable(feature = "ordering_helpers", since = "1.53.0")]
390 pub const fn is_lt(self) -> bool {
394 /// Returns `true` if the ordering is the `Greater` variant.
399 /// use std::cmp::Ordering;
401 /// assert_eq!(Ordering::Less.is_gt(), false);
402 /// assert_eq!(Ordering::Equal.is_gt(), false);
403 /// assert_eq!(Ordering::Greater.is_gt(), true);
407 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
408 #[stable(feature = "ordering_helpers", since = "1.53.0")]
409 pub const fn is_gt(self) -> bool {
410 matches!(self, Greater)
413 /// Returns `true` if the ordering is either the `Less` or `Equal` variant.
418 /// use std::cmp::Ordering;
420 /// assert_eq!(Ordering::Less.is_le(), true);
421 /// assert_eq!(Ordering::Equal.is_le(), true);
422 /// assert_eq!(Ordering::Greater.is_le(), false);
426 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
427 #[stable(feature = "ordering_helpers", since = "1.53.0")]
428 pub const fn is_le(self) -> bool {
429 !matches!(self, Greater)
432 /// Returns `true` if the ordering is either the `Greater` or `Equal` variant.
437 /// use std::cmp::Ordering;
439 /// assert_eq!(Ordering::Less.is_ge(), false);
440 /// assert_eq!(Ordering::Equal.is_ge(), true);
441 /// assert_eq!(Ordering::Greater.is_ge(), true);
445 #[rustc_const_stable(feature = "ordering_helpers", since = "1.53.0")]
446 #[stable(feature = "ordering_helpers", since = "1.53.0")]
447 pub const fn is_ge(self) -> bool {
448 !matches!(self, Less)
451 /// Reverses the `Ordering`.
453 /// * `Less` becomes `Greater`.
454 /// * `Greater` becomes `Less`.
455 /// * `Equal` becomes `Equal`.
462 /// use std::cmp::Ordering;
464 /// assert_eq!(Ordering::Less.reverse(), Ordering::Greater);
465 /// assert_eq!(Ordering::Equal.reverse(), Ordering::Equal);
466 /// assert_eq!(Ordering::Greater.reverse(), Ordering::Less);
469 /// This method can be used to reverse a comparison:
472 /// let data: &mut [_] = &mut [2, 10, 5, 8];
474 /// // sort the array from largest to smallest.
475 /// data.sort_by(|a, b| a.cmp(b).reverse());
477 /// let b: &mut [_] = &mut [10, 8, 5, 2];
478 /// assert!(data == b);
482 #[rustc_const_stable(feature = "const_ordering", since = "1.48.0")]
483 #[stable(feature = "rust1", since = "1.0.0")]
484 pub const fn reverse(self) -> Ordering {
492 /// Chains two orderings.
494 /// Returns `self` when it's not `Equal`. Otherwise returns `other`.
499 /// use std::cmp::Ordering;
501 /// let result = Ordering::Equal.then(Ordering::Less);
502 /// assert_eq!(result, Ordering::Less);
504 /// let result = Ordering::Less.then(Ordering::Equal);
505 /// assert_eq!(result, Ordering::Less);
507 /// let result = Ordering::Less.then(Ordering::Greater);
508 /// assert_eq!(result, Ordering::Less);
510 /// let result = Ordering::Equal.then(Ordering::Equal);
511 /// assert_eq!(result, Ordering::Equal);
513 /// let x: (i64, i64, i64) = (1, 2, 7);
514 /// let y: (i64, i64, i64) = (1, 5, 3);
515 /// let result = x.0.cmp(&y.0).then(x.1.cmp(&y.1)).then(x.2.cmp(&y.2));
517 /// assert_eq!(result, Ordering::Less);
521 #[rustc_const_stable(feature = "const_ordering", since = "1.48.0")]
522 #[stable(feature = "ordering_chaining", since = "1.17.0")]
523 pub const fn then(self, other: Ordering) -> Ordering {
530 /// Chains the ordering with the given function.
532 /// Returns `self` when it's not `Equal`. Otherwise calls `f` and returns
538 /// use std::cmp::Ordering;
540 /// let result = Ordering::Equal.then_with(|| Ordering::Less);
541 /// assert_eq!(result, Ordering::Less);
543 /// let result = Ordering::Less.then_with(|| Ordering::Equal);
544 /// assert_eq!(result, Ordering::Less);
546 /// let result = Ordering::Less.then_with(|| Ordering::Greater);
547 /// assert_eq!(result, Ordering::Less);
549 /// let result = Ordering::Equal.then_with(|| Ordering::Equal);
550 /// assert_eq!(result, Ordering::Equal);
552 /// let x: (i64, i64, i64) = (1, 2, 7);
553 /// let y: (i64, i64, i64) = (1, 5, 3);
554 /// let result = x.0.cmp(&y.0).then_with(|| x.1.cmp(&y.1)).then_with(|| x.2.cmp(&y.2));
556 /// assert_eq!(result, Ordering::Less);
560 #[stable(feature = "ordering_chaining", since = "1.17.0")]
561 pub fn then_with<F: FnOnce() -> Ordering>(self, f: F) -> Ordering {
569 /// A helper struct for reverse ordering.
571 /// This struct is a helper to be used with functions like [`Vec::sort_by_key`] and
572 /// can be used to reverse order a part of a key.
574 /// [`Vec::sort_by_key`]: ../../std/vec/struct.Vec.html#method.sort_by_key
579 /// use std::cmp::Reverse;
581 /// let mut v = vec![1, 2, 3, 4, 5, 6];
582 /// v.sort_by_key(|&num| (num > 3, Reverse(num)));
583 /// assert_eq!(v, vec![3, 2, 1, 6, 5, 4]);
585 #[derive(PartialEq, Eq, Debug, Copy, Default, Hash)]
586 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
588 pub struct Reverse<T>(#[stable(feature = "reverse_cmp_key", since = "1.19.0")] pub T);
590 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
591 impl<T: PartialOrd> PartialOrd for Reverse<T> {
593 fn partial_cmp(&self, other: &Reverse<T>) -> Option<Ordering> {
594 other.0.partial_cmp(&self.0)
598 fn lt(&self, other: &Self) -> bool {
602 fn le(&self, other: &Self) -> bool {
606 fn gt(&self, other: &Self) -> bool {
610 fn ge(&self, other: &Self) -> bool {
615 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
616 impl<T: Ord> Ord for Reverse<T> {
618 fn cmp(&self, other: &Reverse<T>) -> Ordering {
623 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
624 impl<T: Clone> Clone for Reverse<T> {
626 fn clone(&self) -> Reverse<T> {
627 Reverse(self.0.clone())
631 fn clone_from(&mut self, other: &Self) {
632 self.0.clone_from(&other.0)
636 /// Trait for types that form a [total order](https://en.wikipedia.org/wiki/Total_order).
638 /// Implementations must be consistent with the [`PartialOrd`] implementation, and ensure
639 /// `max`, `min`, and `clamp` are consistent with `cmp`:
641 /// - `partial_cmp(a, b) == Some(cmp(a, b))`.
642 /// - `max(a, b) == max_by(a, b, cmp)` (ensured by the default implementation).
643 /// - `min(a, b) == min_by(a, b, cmp)` (ensured by the default implementation).
644 /// - For `a.clamp(min, max)`, see the [method docs](#method.clamp)
645 /// (ensured by the default implementation).
647 /// It's easy to accidentally make `cmp` and `partial_cmp` disagree by
648 /// deriving some of the traits and manually implementing others.
652 /// From the above and the requirements of `PartialOrd`, it follows that `<` defines a strict total order.
653 /// This means that for all `a`, `b` and `c`:
655 /// - exactly one of `a < b`, `a == b` or `a > b` is true; and
656 /// - `<` is transitive: `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
660 /// This trait can be used with `#[derive]`. When `derive`d on structs, it will produce a
661 /// [lexicographic](https://en.wikipedia.org/wiki/Lexicographic_order) ordering based on the top-to-bottom declaration order of the struct's members.
662 /// When `derive`d on enums, variants are ordered by their top-to-bottom discriminant order.
664 /// ## Lexicographical comparison
666 /// Lexicographical comparison is an operation with the following properties:
667 /// - Two sequences are compared element by element.
668 /// - The first mismatching element defines which sequence is lexicographically less or greater than the other.
669 /// - If one sequence is a prefix of another, the shorter sequence is lexicographically less than the other.
670 /// - If two sequence have equivalent elements and are of the same length, then the sequences are lexicographically equal.
671 /// - An empty sequence is lexicographically less than any non-empty sequence.
672 /// - Two empty sequences are lexicographically equal.
674 /// ## How can I implement `Ord`?
676 /// `Ord` requires that the type also be [`PartialOrd`] and [`Eq`] (which requires [`PartialEq`]).
678 /// Then you must define an implementation for [`cmp`]. You may find it useful to use
679 /// [`cmp`] on your type's fields.
681 /// Here's an example where you want to sort people by height only, disregarding `id`
685 /// use std::cmp::Ordering;
694 /// impl Ord for Person {
695 /// fn cmp(&self, other: &Self) -> Ordering {
696 /// self.height.cmp(&other.height)
700 /// impl PartialOrd for Person {
701 /// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
702 /// Some(self.cmp(other))
706 /// impl PartialEq for Person {
707 /// fn eq(&self, other: &Self) -> bool {
708 /// self.height == other.height
713 /// [`cmp`]: Ord::cmp
718 #[stable(feature = "rust1", since = "1.0.0")]
719 pub trait Ord: Eq + PartialOrd<Self> {
720 /// This method returns an [`Ordering`] between `self` and `other`.
722 /// By convention, `self.cmp(&other)` returns the ordering matching the expression
723 /// `self <operator> other` if true.
728 /// use std::cmp::Ordering;
730 /// assert_eq!(5.cmp(&10), Ordering::Less);
731 /// assert_eq!(10.cmp(&5), Ordering::Greater);
732 /// assert_eq!(5.cmp(&5), Ordering::Equal);
735 #[stable(feature = "rust1", since = "1.0.0")]
736 fn cmp(&self, other: &Self) -> Ordering;
738 /// Compares and returns the maximum of two values.
740 /// Returns the second argument if the comparison determines them to be equal.
745 /// assert_eq!(2, 1.max(2));
746 /// assert_eq!(2, 2.max(2));
748 #[stable(feature = "ord_max_min", since = "1.21.0")]
751 fn max(self, other: Self) -> Self
755 max_by(self, other, Ord::cmp)
758 /// Compares and returns the minimum of two values.
760 /// Returns the first argument if the comparison determines them to be equal.
765 /// assert_eq!(1, 1.min(2));
766 /// assert_eq!(2, 2.min(2));
768 #[stable(feature = "ord_max_min", since = "1.21.0")]
771 fn min(self, other: Self) -> Self
775 min_by(self, other, Ord::cmp)
778 /// Restrict a value to a certain interval.
780 /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
781 /// less than `min`. Otherwise this returns `self`.
785 /// Panics if `min > max`.
790 /// assert!((-3).clamp(-2, 1) == -2);
791 /// assert!(0.clamp(-2, 1) == 0);
792 /// assert!(2.clamp(-2, 1) == 1);
795 #[stable(feature = "clamp", since = "1.50.0")]
796 fn clamp(self, min: Self, max: Self) -> Self
803 } else if self > max {
811 /// Derive macro generating an impl of the trait `Ord`.
812 #[rustc_builtin_macro]
813 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
814 #[allow_internal_unstable(core_intrinsics)]
815 pub macro Ord($item:item) {
816 /* compiler built-in */
819 #[stable(feature = "rust1", since = "1.0.0")]
820 impl Eq for Ordering {}
822 #[stable(feature = "rust1", since = "1.0.0")]
823 impl Ord for Ordering {
825 fn cmp(&self, other: &Ordering) -> Ordering {
826 (*self as i32).cmp(&(*other as i32))
830 #[stable(feature = "rust1", since = "1.0.0")]
831 impl PartialOrd for Ordering {
833 fn partial_cmp(&self, other: &Ordering) -> Option<Ordering> {
834 (*self as i32).partial_cmp(&(*other as i32))
838 /// Trait for values that can be compared for a sort-order.
840 /// The `lt`, `le`, `gt`, and `ge` methods of this trait can be called using
841 /// the `<`, `<=`, `>`, and `>=` operators, respectively.
843 /// The methods of this trait must be consistent with each other and with those of `PartialEq` in
844 /// the following sense:
846 /// - `a == b` if and only if `partial_cmp(a, b) == Some(Equal)`.
847 /// - `a < b` if and only if `partial_cmp(a, b) == Some(Less)`
848 /// (ensured by the default implementation).
849 /// - `a > b` if and only if `partial_cmp(a, b) == Some(Greater)`
850 /// (ensured by the default implementation).
851 /// - `a <= b` if and only if `a < b || a == b`
852 /// (ensured by the default implementation).
853 /// - `a >= b` if and only if `a > b || a == b`
854 /// (ensured by the default implementation).
855 /// - `a != b` if and only if `!(a == b)` (already part of `PartialEq`).
857 /// If [`Ord`] is also implemented for `Self` and `Rhs`, it must also be consistent with
858 /// `partial_cmp` (see the documentation of that trait for the exact requirements). It's
859 /// easy to accidentally make them disagree by deriving some of the traits and manually
860 /// implementing others.
862 /// The comparison must satisfy, for all `a`, `b` and `c`:
864 /// - transitivity: `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
865 /// - duality: `a < b` if and only if `b > a`.
867 /// Note that these requirements mean that the trait itself must be implemented symmetrically and
868 /// transitively: if `T: PartialOrd<U>` and `U: PartialOrd<V>` then `U: PartialOrd<T>` and `T:
873 /// The following corollaries follow from the above requirements:
875 /// - irreflexivity of `<` and `>`: `!(a < a)`, `!(a > a)`
876 /// - transitivity of `>`: if `a > b` and `b > c` then `a > c`
877 /// - duality of `partial_cmp`: `partial_cmp(a, b) == partial_cmp(b, a).map(Ordering::reverse)`
881 /// This trait can be used with `#[derive]`. When `derive`d on structs, it will produce a
882 /// lexicographic ordering based on the top-to-bottom declaration order of the struct's members.
883 /// When `derive`d on enums, variants are ordered by their top-to-bottom discriminant order.
885 /// ## How can I implement `PartialOrd`?
887 /// `PartialOrd` only requires implementation of the [`partial_cmp`] method, with the others
888 /// generated from default implementations.
890 /// However it remains possible to implement the others separately for types which do not have a
891 /// total order. For example, for floating point numbers, `NaN < 0 == false` and `NaN >= 0 ==
892 /// false` (cf. IEEE 754-2008 section 5.11).
894 /// `PartialOrd` requires your type to be [`PartialEq`].
896 /// If your type is [`Ord`], you can implement [`partial_cmp`] by using [`cmp`]:
899 /// use std::cmp::Ordering;
908 /// impl PartialOrd for Person {
909 /// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
910 /// Some(self.cmp(other))
914 /// impl Ord for Person {
915 /// fn cmp(&self, other: &Self) -> Ordering {
916 /// self.height.cmp(&other.height)
920 /// impl PartialEq for Person {
921 /// fn eq(&self, other: &Self) -> bool {
922 /// self.height == other.height
927 /// You may also find it useful to use [`partial_cmp`] on your type's fields. Here
928 /// is an example of `Person` types who have a floating-point `height` field that
929 /// is the only field to be used for sorting:
932 /// use std::cmp::Ordering;
940 /// impl PartialOrd for Person {
941 /// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
942 /// self.height.partial_cmp(&other.height)
946 /// impl PartialEq for Person {
947 /// fn eq(&self, other: &Self) -> bool {
948 /// self.height == other.height
959 /// assert_eq!(x < y, true);
960 /// assert_eq!(x.lt(&y), true);
963 /// [`partial_cmp`]: PartialOrd::partial_cmp
964 /// [`cmp`]: Ord::cmp
965 #[lang = "partial_ord"]
966 #[stable(feature = "rust1", since = "1.0.0")]
971 #[rustc_on_unimplemented(
972 message = "can't compare `{Self}` with `{Rhs}`",
973 label = "no implementation for `{Self} < {Rhs}` and `{Self} > {Rhs}`"
975 pub trait PartialOrd<Rhs: ?Sized = Self>: PartialEq<Rhs> {
976 /// This method returns an ordering between `self` and `other` values if one exists.
981 /// use std::cmp::Ordering;
983 /// let result = 1.0.partial_cmp(&2.0);
984 /// assert_eq!(result, Some(Ordering::Less));
986 /// let result = 1.0.partial_cmp(&1.0);
987 /// assert_eq!(result, Some(Ordering::Equal));
989 /// let result = 2.0.partial_cmp(&1.0);
990 /// assert_eq!(result, Some(Ordering::Greater));
993 /// When comparison is impossible:
996 /// let result = f64::NAN.partial_cmp(&1.0);
997 /// assert_eq!(result, None);
1000 #[stable(feature = "rust1", since = "1.0.0")]
1001 fn partial_cmp(&self, other: &Rhs) -> Option<Ordering>;
1003 /// This method tests less than (for `self` and `other`) and is used by the `<` operator.
1008 /// let result = 1.0 < 2.0;
1009 /// assert_eq!(result, true);
1011 /// let result = 2.0 < 1.0;
1012 /// assert_eq!(result, false);
1016 #[stable(feature = "rust1", since = "1.0.0")]
1017 fn lt(&self, other: &Rhs) -> bool {
1018 matches!(self.partial_cmp(other), Some(Less))
1021 /// This method tests less than or equal to (for `self` and `other`) and is used by the `<=`
1027 /// let result = 1.0 <= 2.0;
1028 /// assert_eq!(result, true);
1030 /// let result = 2.0 <= 2.0;
1031 /// assert_eq!(result, true);
1035 #[stable(feature = "rust1", since = "1.0.0")]
1036 fn le(&self, other: &Rhs) -> bool {
1037 // Pattern `Some(Less | Eq)` optimizes worse than negating `None | Some(Greater)`.
1038 // FIXME: The root cause was fixed upstream in LLVM with:
1039 // https://github.com/llvm/llvm-project/commit/9bad7de9a3fb844f1ca2965f35d0c2a3d1e11775
1040 // Revert this workaround once support for LLVM 12 gets dropped.
1041 !matches!(self.partial_cmp(other), None | Some(Greater))
1044 /// This method tests greater than (for `self` and `other`) and is used by the `>` operator.
1049 /// let result = 1.0 > 2.0;
1050 /// assert_eq!(result, false);
1052 /// let result = 2.0 > 2.0;
1053 /// assert_eq!(result, false);
1057 #[stable(feature = "rust1", since = "1.0.0")]
1058 fn gt(&self, other: &Rhs) -> bool {
1059 matches!(self.partial_cmp(other), Some(Greater))
1062 /// This method tests greater than or equal to (for `self` and `other`) and is used by the `>=`
1068 /// let result = 2.0 >= 1.0;
1069 /// assert_eq!(result, true);
1071 /// let result = 2.0 >= 2.0;
1072 /// assert_eq!(result, true);
1076 #[stable(feature = "rust1", since = "1.0.0")]
1077 fn ge(&self, other: &Rhs) -> bool {
1078 matches!(self.partial_cmp(other), Some(Greater | Equal))
1082 /// Derive macro generating an impl of the trait `PartialOrd`.
1083 #[rustc_builtin_macro]
1084 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
1085 #[allow_internal_unstable(core_intrinsics)]
1086 pub macro PartialOrd($item:item) {
1087 /* compiler built-in */
1090 /// Compares and returns the minimum of two values.
1092 /// Returns the first argument if the comparison determines them to be equal.
1094 /// Internally uses an alias to [`Ord::min`].
1101 /// assert_eq!(1, cmp::min(1, 2));
1102 /// assert_eq!(2, cmp::min(2, 2));
1106 #[stable(feature = "rust1", since = "1.0.0")]
1107 #[cfg_attr(not(test), rustc_diagnostic_item = "cmp_min")]
1108 pub fn min<T: Ord>(v1: T, v2: T) -> T {
1112 /// Returns the minimum of two values with respect to the specified comparison function.
1114 /// Returns the first argument if the comparison determines them to be equal.
1121 /// assert_eq!(cmp::min_by(-2, 1, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), 1);
1122 /// assert_eq!(cmp::min_by(-2, 2, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), -2);
1126 #[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1127 pub fn min_by<T, F: FnOnce(&T, &T) -> Ordering>(v1: T, v2: T, compare: F) -> T {
1128 match compare(&v1, &v2) {
1129 Ordering::Less | Ordering::Equal => v1,
1130 Ordering::Greater => v2,
1134 /// Returns the element that gives the minimum value from the specified function.
1136 /// Returns the first argument if the comparison determines them to be equal.
1143 /// assert_eq!(cmp::min_by_key(-2, 1, |x: &i32| x.abs()), 1);
1144 /// assert_eq!(cmp::min_by_key(-2, 2, |x: &i32| x.abs()), -2);
1148 #[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1149 pub fn min_by_key<T, F: FnMut(&T) -> K, K: Ord>(v1: T, v2: T, mut f: F) -> T {
1150 min_by(v1, v2, |v1, v2| f(v1).cmp(&f(v2)))
1153 /// Compares and returns the maximum of two values.
1155 /// Returns the second argument if the comparison determines them to be equal.
1157 /// Internally uses an alias to [`Ord::max`].
1164 /// assert_eq!(2, cmp::max(1, 2));
1165 /// assert_eq!(2, cmp::max(2, 2));
1169 #[stable(feature = "rust1", since = "1.0.0")]
1170 #[cfg_attr(not(test), rustc_diagnostic_item = "cmp_max")]
1171 pub fn max<T: Ord>(v1: T, v2: T) -> T {
1175 /// Returns the maximum of two values with respect to the specified comparison function.
1177 /// Returns the second argument if the comparison determines them to be equal.
1184 /// assert_eq!(cmp::max_by(-2, 1, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), -2);
1185 /// assert_eq!(cmp::max_by(-2, 2, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), 2);
1189 #[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1190 pub fn max_by<T, F: FnOnce(&T, &T) -> Ordering>(v1: T, v2: T, compare: F) -> T {
1191 match compare(&v1, &v2) {
1192 Ordering::Less | Ordering::Equal => v2,
1193 Ordering::Greater => v1,
1197 /// Returns the element that gives the maximum value from the specified function.
1199 /// Returns the second argument if the comparison determines them to be equal.
1206 /// assert_eq!(cmp::max_by_key(-2, 1, |x: &i32| x.abs()), -2);
1207 /// assert_eq!(cmp::max_by_key(-2, 2, |x: &i32| x.abs()), 2);
1211 #[stable(feature = "cmp_min_max_by", since = "1.53.0")]
1212 pub fn max_by_key<T, F: FnMut(&T) -> K, K: Ord>(v1: T, v2: T, mut f: F) -> T {
1213 max_by(v1, v2, |v1, v2| f(v1).cmp(&f(v2)))
1216 // Implementation of PartialEq, Eq, PartialOrd and Ord for primitive types
1218 use crate::cmp::Ordering::{self, Equal, Greater, Less};
1219 use crate::hint::unreachable_unchecked;
1221 macro_rules! partial_eq_impl {
1223 #[stable(feature = "rust1", since = "1.0.0")]
1224 impl PartialEq for $t {
1226 fn eq(&self, other: &$t) -> bool { (*self) == (*other) }
1228 fn ne(&self, other: &$t) -> bool { (*self) != (*other) }
1233 #[stable(feature = "rust1", since = "1.0.0")]
1234 impl PartialEq for () {
1236 fn eq(&self, _other: &()) -> bool {
1240 fn ne(&self, _other: &()) -> bool {
1246 bool char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64
1249 macro_rules! eq_impl {
1251 #[stable(feature = "rust1", since = "1.0.0")]
1256 eq_impl! { () bool char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1258 macro_rules! partial_ord_impl {
1260 #[stable(feature = "rust1", since = "1.0.0")]
1261 impl PartialOrd for $t {
1263 fn partial_cmp(&self, other: &$t) -> Option<Ordering> {
1264 match (self <= other, self >= other) {
1265 (false, false) => None,
1266 (false, true) => Some(Greater),
1267 (true, false) => Some(Less),
1268 (true, true) => Some(Equal),
1272 fn lt(&self, other: &$t) -> bool { (*self) < (*other) }
1274 fn le(&self, other: &$t) -> bool { (*self) <= (*other) }
1276 fn ge(&self, other: &$t) -> bool { (*self) >= (*other) }
1278 fn gt(&self, other: &$t) -> bool { (*self) > (*other) }
1283 #[stable(feature = "rust1", since = "1.0.0")]
1284 impl PartialOrd for () {
1286 fn partial_cmp(&self, _: &()) -> Option<Ordering> {
1291 #[stable(feature = "rust1", since = "1.0.0")]
1292 impl PartialOrd for bool {
1294 fn partial_cmp(&self, other: &bool) -> Option<Ordering> {
1295 Some(self.cmp(other))
1299 partial_ord_impl! { f32 f64 }
1301 macro_rules! ord_impl {
1303 #[stable(feature = "rust1", since = "1.0.0")]
1304 impl PartialOrd for $t {
1306 fn partial_cmp(&self, other: &$t) -> Option<Ordering> {
1307 Some(self.cmp(other))
1310 fn lt(&self, other: &$t) -> bool { (*self) < (*other) }
1312 fn le(&self, other: &$t) -> bool { (*self) <= (*other) }
1314 fn ge(&self, other: &$t) -> bool { (*self) >= (*other) }
1316 fn gt(&self, other: &$t) -> bool { (*self) > (*other) }
1319 #[stable(feature = "rust1", since = "1.0.0")]
1322 fn cmp(&self, other: &$t) -> Ordering {
1323 // The order here is important to generate more optimal assembly.
1324 // See <https://github.com/rust-lang/rust/issues/63758> for more info.
1325 if *self < *other { Less }
1326 else if *self == *other { Equal }
1333 #[stable(feature = "rust1", since = "1.0.0")]
1336 fn cmp(&self, _other: &()) -> Ordering {
1341 #[stable(feature = "rust1", since = "1.0.0")]
1344 fn cmp(&self, other: &bool) -> Ordering {
1345 // Casting to i8's and converting the difference to an Ordering generates
1346 // more optimal assembly.
1347 // See <https://github.com/rust-lang/rust/issues/66780> for more info.
1348 match (*self as i8) - (*other as i8) {
1352 // SAFETY: bool as i8 returns 0 or 1, so the difference can't be anything else
1353 _ => unsafe { unreachable_unchecked() },
1358 ord_impl! { char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1360 #[unstable(feature = "never_type", issue = "35121")]
1361 impl PartialEq for ! {
1362 fn eq(&self, _: &!) -> bool {
1367 #[unstable(feature = "never_type", issue = "35121")]
1370 #[unstable(feature = "never_type", issue = "35121")]
1371 impl PartialOrd for ! {
1372 fn partial_cmp(&self, _: &!) -> Option<Ordering> {
1377 #[unstable(feature = "never_type", issue = "35121")]
1379 fn cmp(&self, _: &!) -> Ordering {
1386 #[stable(feature = "rust1", since = "1.0.0")]
1387 impl<A: ?Sized, B: ?Sized> PartialEq<&B> for &A
1392 fn eq(&self, other: &&B) -> bool {
1393 PartialEq::eq(*self, *other)
1396 fn ne(&self, other: &&B) -> bool {
1397 PartialEq::ne(*self, *other)
1400 #[stable(feature = "rust1", since = "1.0.0")]
1401 impl<A: ?Sized, B: ?Sized> PartialOrd<&B> for &A
1406 fn partial_cmp(&self, other: &&B) -> Option<Ordering> {
1407 PartialOrd::partial_cmp(*self, *other)
1410 fn lt(&self, other: &&B) -> bool {
1411 PartialOrd::lt(*self, *other)
1414 fn le(&self, other: &&B) -> bool {
1415 PartialOrd::le(*self, *other)
1418 fn gt(&self, other: &&B) -> bool {
1419 PartialOrd::gt(*self, *other)
1422 fn ge(&self, other: &&B) -> bool {
1423 PartialOrd::ge(*self, *other)
1426 #[stable(feature = "rust1", since = "1.0.0")]
1427 impl<A: ?Sized> Ord for &A
1432 fn cmp(&self, other: &Self) -> Ordering {
1433 Ord::cmp(*self, *other)
1436 #[stable(feature = "rust1", since = "1.0.0")]
1437 impl<A: ?Sized> Eq for &A where A: Eq {}
1441 #[stable(feature = "rust1", since = "1.0.0")]
1442 impl<A: ?Sized, B: ?Sized> PartialEq<&mut B> for &mut A
1447 fn eq(&self, other: &&mut B) -> bool {
1448 PartialEq::eq(*self, *other)
1451 fn ne(&self, other: &&mut B) -> bool {
1452 PartialEq::ne(*self, *other)
1455 #[stable(feature = "rust1", since = "1.0.0")]
1456 impl<A: ?Sized, B: ?Sized> PartialOrd<&mut B> for &mut A
1461 fn partial_cmp(&self, other: &&mut B) -> Option<Ordering> {
1462 PartialOrd::partial_cmp(*self, *other)
1465 fn lt(&self, other: &&mut B) -> bool {
1466 PartialOrd::lt(*self, *other)
1469 fn le(&self, other: &&mut B) -> bool {
1470 PartialOrd::le(*self, *other)
1473 fn gt(&self, other: &&mut B) -> bool {
1474 PartialOrd::gt(*self, *other)
1477 fn ge(&self, other: &&mut B) -> bool {
1478 PartialOrd::ge(*self, *other)
1481 #[stable(feature = "rust1", since = "1.0.0")]
1482 impl<A: ?Sized> Ord for &mut A
1487 fn cmp(&self, other: &Self) -> Ordering {
1488 Ord::cmp(*self, *other)
1491 #[stable(feature = "rust1", since = "1.0.0")]
1492 impl<A: ?Sized> Eq for &mut A where A: Eq {}
1494 #[stable(feature = "rust1", since = "1.0.0")]
1495 impl<A: ?Sized, B: ?Sized> PartialEq<&mut B> for &A
1500 fn eq(&self, other: &&mut B) -> bool {
1501 PartialEq::eq(*self, *other)
1504 fn ne(&self, other: &&mut B) -> bool {
1505 PartialEq::ne(*self, *other)
1509 #[stable(feature = "rust1", since = "1.0.0")]
1510 impl<A: ?Sized, B: ?Sized> PartialEq<&B> for &mut A
1515 fn eq(&self, other: &&B) -> bool {
1516 PartialEq::eq(*self, *other)
1519 fn ne(&self, other: &&B) -> bool {
1520 PartialEq::ne(*self, *other)