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 /// This trait allows for partial equality, for types that do not have a full
31 /// equivalence relation. For example, in floating point numbers `NaN != NaN`,
32 /// so floating point types implement `PartialEq` but not [`trait@Eq`].
34 /// Formally, the equality must be (for all `a`, `b`, `c` of type `A`, `B`,
37 /// - **Symmetric**: if `A: PartialEq<B>` and `B: PartialEq<A>`, then **`a == b`
38 /// implies `b == a`**; and
40 /// - **Transitive**: if `A: PartialEq<B>` and `B: PartialEq<C>` and `A:
41 /// PartialEq<C>`, then **`a == b` and `b == c` implies `a == c`**.
43 /// Note that the `B: PartialEq<A>` (symmetric) and `A: PartialEq<C>`
44 /// (transitive) impls are not forced to exist, but these requirements apply
45 /// whenever they do exist.
49 /// This trait can be used with `#[derive]`. When `derive`d on structs, two
50 /// instances are equal if all fields are equal, and not equal if any fields
51 /// are not equal. When `derive`d on enums, each variant is equal to itself
52 /// and not equal to the other variants.
54 /// ## How can I implement `PartialEq`?
56 /// `PartialEq` only requires the [`eq`] method to be implemented; [`ne`] is defined
57 /// in terms of it by default. Any manual implementation of [`ne`] *must* respect
58 /// the rule that [`eq`] is a strict inverse of [`ne`]; that is, `!(a == b)` if and
61 /// Implementations of `PartialEq`, [`PartialOrd`], and [`Ord`] *must* agree with
62 /// each other. It's easy to accidentally make them disagree by deriving some
63 /// of the traits and manually implementing others.
65 /// An example implementation for a domain in which two books are considered
66 /// the same book if their ISBN matches, even if the formats differ:
77 /// format: BookFormat,
80 /// impl PartialEq for Book {
81 /// fn eq(&self, other: &Self) -> bool {
82 /// self.isbn == other.isbn
86 /// let b1 = Book { isbn: 3, format: BookFormat::Paperback };
87 /// let b2 = Book { isbn: 3, format: BookFormat::Ebook };
88 /// let b3 = Book { isbn: 10, format: BookFormat::Paperback };
90 /// assert!(b1 == b2);
91 /// assert!(b1 != b3);
94 /// ## How can I compare two different types?
96 /// The type you can compare with is controlled by `PartialEq`'s type parameter.
97 /// For example, let's tweak our previous code a bit:
100 /// // The derive implements <BookFormat> == <BookFormat> comparisons
101 /// #[derive(PartialEq)]
102 /// enum BookFormat {
110 /// format: BookFormat,
113 /// // Implement <Book> == <BookFormat> comparisons
114 /// impl PartialEq<BookFormat> for Book {
115 /// fn eq(&self, other: &BookFormat) -> bool {
116 /// self.format == *other
120 /// // Implement <BookFormat> == <Book> comparisons
121 /// impl PartialEq<Book> for BookFormat {
122 /// fn eq(&self, other: &Book) -> bool {
123 /// *self == other.format
127 /// let b1 = Book { isbn: 3, format: BookFormat::Paperback };
129 /// assert!(b1 == BookFormat::Paperback);
130 /// assert!(BookFormat::Ebook != b1);
133 /// By changing `impl PartialEq for Book` to `impl PartialEq<BookFormat> for Book`,
134 /// we allow `BookFormat`s to be compared with `Book`s.
136 /// A comparison like the one above, which ignores some fields of the struct,
137 /// can be dangerous. It can easily lead to an unintended violation of the
138 /// requirements for a partial equivalence relation. For example, if we kept
139 /// the above implementation of `PartialEq<Book>` for `BookFormat` and added an
140 /// implementation of `PartialEq<Book>` for `Book` (either via a `#[derive]` or
141 /// via the manual implementation from the first example) then the result would
142 /// violate transitivity:
145 /// #[derive(PartialEq)]
146 /// enum BookFormat {
152 /// #[derive(PartialEq)]
155 /// format: BookFormat,
158 /// impl PartialEq<BookFormat> for Book {
159 /// fn eq(&self, other: &BookFormat) -> bool {
160 /// self.format == *other
164 /// impl PartialEq<Book> for BookFormat {
165 /// fn eq(&self, other: &Book) -> bool {
166 /// *self == other.format
171 /// let b1 = Book { isbn: 1, format: BookFormat::Paperback };
172 /// let b2 = Book { isbn: 2, format: BookFormat::Paperback };
174 /// assert!(b1 == BookFormat::Paperback);
175 /// assert!(BookFormat::Paperback == b2);
177 /// // The following should hold by transitivity but doesn't.
178 /// assert!(b1 == b2); // <-- PANICS
188 /// assert_eq!(x == y, false);
189 /// assert_eq!(x.eq(&y), false);
192 /// [`eq`]: PartialEq::eq
193 /// [`ne`]: PartialEq::ne
195 #[stable(feature = "rust1", since = "1.0.0")]
198 #[rustc_on_unimplemented(
199 message
= "can't compare `{Self}` with `{Rhs}`",
200 label
= "no implementation for `{Self} == {Rhs}`"
202 pub trait PartialEq
<Rhs
: ?Sized
= Self> {
203 /// This method tests for `self` and `other` values to be equal, and is used
206 #[stable(feature = "rust1", since = "1.0.0")]
207 fn eq(&self, other
: &Rhs
) -> bool
;
209 /// This method tests for `!=`.
212 #[stable(feature = "rust1", since = "1.0.0")]
213 fn ne(&self, other
: &Rhs
) -> bool
{
218 /// Derive macro generating an impl of the trait `PartialEq`.
219 #[rustc_builtin_macro]
220 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
221 #[allow_internal_unstable(core_intrinsics, structural_match)]
222 pub macro PartialEq($item
:item
) {
223 /* compiler built-in */
226 /// Trait for equality comparisons which are [equivalence relations](
227 /// https://en.wikipedia.org/wiki/Equivalence_relation).
229 /// This means, that in addition to `a == b` and `a != b` being strict inverses, the equality must
230 /// be (for all `a`, `b` and `c`):
232 /// - reflexive: `a == a`;
233 /// - symmetric: `a == b` implies `b == a`; and
234 /// - transitive: `a == b` and `b == c` implies `a == c`.
236 /// This property cannot be checked by the compiler, and therefore `Eq` implies
237 /// [`PartialEq`], and has no extra methods.
241 /// This trait can be used with `#[derive]`. When `derive`d, because `Eq` has
242 /// no extra methods, it is only informing the compiler that this is an
243 /// equivalence relation rather than a partial equivalence relation. Note that
244 /// the `derive` strategy requires all fields are `Eq`, which isn't
247 /// ## How can I implement `Eq`?
249 /// If you cannot use the `derive` strategy, specify that your type implements
250 /// `Eq`, which has no methods:
253 /// enum BookFormat { Paperback, Hardback, Ebook }
256 /// format: BookFormat,
258 /// impl PartialEq for Book {
259 /// fn eq(&self, other: &Self) -> bool {
260 /// self.isbn == other.isbn
263 /// impl Eq for Book {}
267 #[stable(feature = "rust1", since = "1.0.0")]
268 pub trait Eq
: PartialEq
<Self> {
269 // this method is used solely by #[deriving] to assert
270 // that every component of a type implements #[deriving]
271 // itself, the current deriving infrastructure means doing this
272 // assertion without using a method on this trait is nearly
275 // This should never be implemented by hand.
278 #[stable(feature = "rust1", since = "1.0.0")]
279 fn assert_receiver_is_total_eq(&self) {}
282 /// Derive macro generating an impl of the trait `Eq`.
283 #[rustc_builtin_macro]
284 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
285 #[allow_internal_unstable(core_intrinsics, derive_eq, structural_match)]
286 pub macro Eq($item
:item
) {
287 /* compiler built-in */
290 // FIXME: this struct is used solely by #[derive] to
291 // assert that every component of a type implements Eq.
293 // This struct should never appear in user code.
295 #[allow(missing_debug_implementations)]
296 #[unstable(feature = "derive_eq", reason = "deriving hack, should not be public", issue = "none")]
297 pub struct AssertParamIsEq
<T
: Eq
+ ?Sized
> {
298 _field
: crate::marker
::PhantomData
<T
>,
301 /// An `Ordering` is the result of a comparison between two values.
306 /// use std::cmp::Ordering;
308 /// let result = 1.cmp(&2);
309 /// assert_eq!(Ordering::Less, result);
311 /// let result = 1.cmp(&1);
312 /// assert_eq!(Ordering::Equal, result);
314 /// let result = 2.cmp(&1);
315 /// assert_eq!(Ordering::Greater, result);
317 #[derive(Clone, Copy, PartialEq, Debug, Hash)]
318 #[stable(feature = "rust1", since = "1.0.0")]
320 /// An ordering where a compared value is less than another.
321 #[stable(feature = "rust1", since = "1.0.0")]
323 /// An ordering where a compared value is equal to another.
324 #[stable(feature = "rust1", since = "1.0.0")]
326 /// An ordering where a compared value is greater than another.
327 #[stable(feature = "rust1", since = "1.0.0")]
332 /// Returns `true` if the ordering is the `Equal` variant.
337 /// #![feature(ordering_helpers)]
338 /// use std::cmp::Ordering;
340 /// assert_eq!(Ordering::Less.is_eq(), false);
341 /// assert_eq!(Ordering::Equal.is_eq(), true);
342 /// assert_eq!(Ordering::Greater.is_eq(), false);
346 #[unstable(feature = "ordering_helpers", issue = "79885")]
347 pub const fn is_eq(self) -> bool
{
348 matches
!(self, Equal
)
351 /// Returns `true` if the ordering is not the `Equal` variant.
356 /// #![feature(ordering_helpers)]
357 /// use std::cmp::Ordering;
359 /// assert_eq!(Ordering::Less.is_ne(), true);
360 /// assert_eq!(Ordering::Equal.is_ne(), false);
361 /// assert_eq!(Ordering::Greater.is_ne(), true);
365 #[unstable(feature = "ordering_helpers", issue = "79885")]
366 pub const fn is_ne(self) -> bool
{
367 !matches
!(self, Equal
)
370 /// Returns `true` if the ordering is the `Less` variant.
375 /// #![feature(ordering_helpers)]
376 /// use std::cmp::Ordering;
378 /// assert_eq!(Ordering::Less.is_lt(), true);
379 /// assert_eq!(Ordering::Equal.is_lt(), false);
380 /// assert_eq!(Ordering::Greater.is_lt(), false);
384 #[unstable(feature = "ordering_helpers", issue = "79885")]
385 pub const fn is_lt(self) -> bool
{
389 /// Returns `true` if the ordering is the `Greater` variant.
394 /// #![feature(ordering_helpers)]
395 /// use std::cmp::Ordering;
397 /// assert_eq!(Ordering::Less.is_gt(), false);
398 /// assert_eq!(Ordering::Equal.is_gt(), false);
399 /// assert_eq!(Ordering::Greater.is_gt(), true);
403 #[unstable(feature = "ordering_helpers", issue = "79885")]
404 pub const fn is_gt(self) -> bool
{
405 matches
!(self, Greater
)
408 /// Returns `true` if the ordering is either the `Less` or `Equal` variant.
413 /// #![feature(ordering_helpers)]
414 /// use std::cmp::Ordering;
416 /// assert_eq!(Ordering::Less.is_le(), true);
417 /// assert_eq!(Ordering::Equal.is_le(), true);
418 /// assert_eq!(Ordering::Greater.is_le(), false);
422 #[unstable(feature = "ordering_helpers", issue = "79885")]
423 pub const fn is_le(self) -> bool
{
424 !matches
!(self, Greater
)
427 /// Returns `true` if the ordering is either the `Greater` or `Equal` variant.
432 /// #![feature(ordering_helpers)]
433 /// use std::cmp::Ordering;
435 /// assert_eq!(Ordering::Less.is_ge(), false);
436 /// assert_eq!(Ordering::Equal.is_ge(), true);
437 /// assert_eq!(Ordering::Greater.is_ge(), true);
441 #[unstable(feature = "ordering_helpers", issue = "79885")]
442 pub const fn is_ge(self) -> bool
{
443 !matches
!(self, Less
)
446 /// Reverses the `Ordering`.
448 /// * `Less` becomes `Greater`.
449 /// * `Greater` becomes `Less`.
450 /// * `Equal` becomes `Equal`.
457 /// use std::cmp::Ordering;
459 /// assert_eq!(Ordering::Less.reverse(), Ordering::Greater);
460 /// assert_eq!(Ordering::Equal.reverse(), Ordering::Equal);
461 /// assert_eq!(Ordering::Greater.reverse(), Ordering::Less);
464 /// This method can be used to reverse a comparison:
467 /// let data: &mut [_] = &mut [2, 10, 5, 8];
469 /// // sort the array from largest to smallest.
470 /// data.sort_by(|a, b| a.cmp(b).reverse());
472 /// let b: &mut [_] = &mut [10, 8, 5, 2];
473 /// assert!(data == b);
477 #[rustc_const_stable(feature = "const_ordering", since = "1.48.0")]
478 #[stable(feature = "rust1", since = "1.0.0")]
479 pub const fn reverse(self) -> Ordering
{
487 /// Chains two orderings.
489 /// Returns `self` when it's not `Equal`. Otherwise returns `other`.
494 /// use std::cmp::Ordering;
496 /// let result = Ordering::Equal.then(Ordering::Less);
497 /// assert_eq!(result, Ordering::Less);
499 /// let result = Ordering::Less.then(Ordering::Equal);
500 /// assert_eq!(result, Ordering::Less);
502 /// let result = Ordering::Less.then(Ordering::Greater);
503 /// assert_eq!(result, Ordering::Less);
505 /// let result = Ordering::Equal.then(Ordering::Equal);
506 /// assert_eq!(result, Ordering::Equal);
508 /// let x: (i64, i64, i64) = (1, 2, 7);
509 /// let y: (i64, i64, i64) = (1, 5, 3);
510 /// let result = x.0.cmp(&y.0).then(x.1.cmp(&y.1)).then(x.2.cmp(&y.2));
512 /// assert_eq!(result, Ordering::Less);
516 #[rustc_const_stable(feature = "const_ordering", since = "1.48.0")]
517 #[stable(feature = "ordering_chaining", since = "1.17.0")]
518 pub const fn then(self, other
: Ordering
) -> Ordering
{
525 /// Chains the ordering with the given function.
527 /// Returns `self` when it's not `Equal`. Otherwise calls `f` and returns
533 /// use std::cmp::Ordering;
535 /// let result = Ordering::Equal.then_with(|| Ordering::Less);
536 /// assert_eq!(result, Ordering::Less);
538 /// let result = Ordering::Less.then_with(|| Ordering::Equal);
539 /// assert_eq!(result, Ordering::Less);
541 /// let result = Ordering::Less.then_with(|| Ordering::Greater);
542 /// assert_eq!(result, Ordering::Less);
544 /// let result = Ordering::Equal.then_with(|| Ordering::Equal);
545 /// assert_eq!(result, Ordering::Equal);
547 /// let x: (i64, i64, i64) = (1, 2, 7);
548 /// let y: (i64, i64, i64) = (1, 5, 3);
549 /// let result = x.0.cmp(&y.0).then_with(|| x.1.cmp(&y.1)).then_with(|| x.2.cmp(&y.2));
551 /// assert_eq!(result, Ordering::Less);
555 #[stable(feature = "ordering_chaining", since = "1.17.0")]
556 pub fn then_with
<F
: FnOnce() -> Ordering
>(self, f
: F
) -> Ordering
{
564 /// A helper struct for reverse ordering.
566 /// This struct is a helper to be used with functions like [`Vec::sort_by_key`] and
567 /// can be used to reverse order a part of a key.
569 /// [`Vec::sort_by_key`]: ../../std/vec/struct.Vec.html#method.sort_by_key
574 /// use std::cmp::Reverse;
576 /// let mut v = vec![1, 2, 3, 4, 5, 6];
577 /// v.sort_by_key(|&num| (num > 3, Reverse(num)));
578 /// assert_eq!(v, vec![3, 2, 1, 6, 5, 4]);
580 #[derive(PartialEq, Eq, Debug, Copy, Clone, Default, Hash)]
581 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
582 pub struct Reverse
<T
>(#[stable(feature = "reverse_cmp_key", since = "1.19.0")] pub T);
584 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
585 impl<T
: PartialOrd
> PartialOrd
for Reverse
<T
> {
587 fn partial_cmp(&self, other
: &Reverse
<T
>) -> Option
<Ordering
> {
588 other
.0.partial_cmp(&self.0)
592 fn lt(&self, other
: &Self) -> bool
{
596 fn le(&self, other
: &Self) -> bool
{
600 fn gt(&self, other
: &Self) -> bool
{
604 fn ge(&self, other
: &Self) -> bool
{
609 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
610 impl<T
: Ord
> Ord
for Reverse
<T
> {
612 fn cmp(&self, other
: &Reverse
<T
>) -> Ordering
{
617 /// Trait for types that form a [total order](https://en.wikipedia.org/wiki/Total_order).
619 /// An order is a total order if it is (for all `a`, `b` and `c`):
621 /// - total and asymmetric: exactly one of `a < b`, `a == b` or `a > b` is true; and
622 /// - transitive, `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
626 /// This trait can be used with `#[derive]`. When `derive`d on structs, it will produce a
627 /// [lexicographic](https://en.wikipedia.org/wiki/Lexicographic_order) ordering based on the top-to-bottom declaration order of the struct's members.
628 /// When `derive`d on enums, variants are ordered by their top-to-bottom discriminant order.
630 /// ## Lexicographical comparison
632 /// Lexicographical comparison is an operation with the following properties:
633 /// - Two sequences are compared element by element.
634 /// - The first mismatching element defines which sequence is lexicographically less or greater than the other.
635 /// - If one sequence is a prefix of another, the shorter sequence is lexicographically less than the other.
636 /// - If two sequence have equivalent elements and are of the same length, then the sequences are lexicographically equal.
637 /// - An empty sequence is lexicographically less than any non-empty sequence.
638 /// - Two empty sequences are lexicographically equal.
640 /// ## How can I implement `Ord`?
642 /// `Ord` requires that the type also be [`PartialOrd`] and [`Eq`] (which requires [`PartialEq`]).
644 /// Then you must define an implementation for [`cmp`]. You may find it useful to use
645 /// [`cmp`] on your type's fields.
647 /// Implementations of [`PartialEq`], [`PartialOrd`], and `Ord` *must*
648 /// agree with each other. That is, `a.cmp(b) == Ordering::Equal` if
649 /// and only if `a == b` and `Some(a.cmp(b)) == a.partial_cmp(b)` for
650 /// all `a` and `b`. It's easy to accidentally make them disagree by
651 /// deriving some of the traits and manually implementing others.
653 /// Here's an example where you want to sort people by height only, disregarding `id`
657 /// use std::cmp::Ordering;
666 /// impl Ord for Person {
667 /// fn cmp(&self, other: &Self) -> Ordering {
668 /// self.height.cmp(&other.height)
672 /// impl PartialOrd for Person {
673 /// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
674 /// Some(self.cmp(other))
678 /// impl PartialEq for Person {
679 /// fn eq(&self, other: &Self) -> bool {
680 /// self.height == other.height
685 /// [`cmp`]: Ord::cmp
690 #[stable(feature = "rust1", since = "1.0.0")]
691 pub trait Ord
: Eq
+ PartialOrd
<Self> {
692 /// This method returns an [`Ordering`] between `self` and `other`.
694 /// By convention, `self.cmp(&other)` returns the ordering matching the expression
695 /// `self <operator> other` if true.
700 /// use std::cmp::Ordering;
702 /// assert_eq!(5.cmp(&10), Ordering::Less);
703 /// assert_eq!(10.cmp(&5), Ordering::Greater);
704 /// assert_eq!(5.cmp(&5), Ordering::Equal);
707 #[stable(feature = "rust1", since = "1.0.0")]
708 fn cmp(&self, other
: &Self) -> Ordering
;
710 /// Compares and returns the maximum of two values.
712 /// Returns the second argument if the comparison determines them to be equal.
717 /// assert_eq!(2, 1.max(2));
718 /// assert_eq!(2, 2.max(2));
720 #[stable(feature = "ord_max_min", since = "1.21.0")]
723 fn max(self, other
: Self) -> Self
727 max_by(self, other
, Ord
::cmp
)
730 /// Compares and returns the minimum of two values.
732 /// Returns the first argument if the comparison determines them to be equal.
737 /// assert_eq!(1, 1.min(2));
738 /// assert_eq!(2, 2.min(2));
740 #[stable(feature = "ord_max_min", since = "1.21.0")]
743 fn min(self, other
: Self) -> Self
747 min_by(self, other
, Ord
::cmp
)
750 /// Restrict a value to a certain interval.
752 /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
753 /// less than `min`. Otherwise this returns `self`.
757 /// Panics if `min > max`.
762 /// assert!((-3).clamp(-2, 1) == -2);
763 /// assert!(0.clamp(-2, 1) == 0);
764 /// assert!(2.clamp(-2, 1) == 1);
767 #[stable(feature = "clamp", since = "1.50.0")]
768 fn clamp(self, min
: Self, max
: Self) -> Self
775 } else if self > max
{
783 /// Derive macro generating an impl of the trait `Ord`.
784 #[rustc_builtin_macro]
785 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
786 #[allow_internal_unstable(core_intrinsics)]
787 pub macro Ord($item
:item
) {
788 /* compiler built-in */
791 #[stable(feature = "rust1", since = "1.0.0")]
792 impl Eq
for Ordering {}
794 #[stable(feature = "rust1", since = "1.0.0")]
795 impl Ord
for Ordering
{
797 fn cmp(&self, other
: &Ordering
) -> Ordering
{
798 (*self as i32).cmp(&(*other
as i32))
802 #[stable(feature = "rust1", since = "1.0.0")]
803 impl PartialOrd
for Ordering
{
805 fn partial_cmp(&self, other
: &Ordering
) -> Option
<Ordering
> {
806 (*self as i32).partial_cmp(&(*other
as i32))
810 /// Trait for values that can be compared for a sort-order.
812 /// The comparison must satisfy, for all `a`, `b` and `c`:
814 /// - asymmetry: if `a < b` then `!(a > b)`, as well as `a > b` implying `!(a < b)`; and
815 /// - transitivity: `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
817 /// Note that these requirements mean that the trait itself must be implemented symmetrically and
818 /// transitively: if `T: PartialOrd<U>` and `U: PartialOrd<V>` then `U: PartialOrd<T>` and `T:
823 /// This trait can be used with `#[derive]`. When `derive`d on structs, it will produce a
824 /// lexicographic ordering based on the top-to-bottom declaration order of the struct's members.
825 /// When `derive`d on enums, variants are ordered by their top-to-bottom discriminant order.
827 /// ## How can I implement `PartialOrd`?
829 /// `PartialOrd` only requires implementation of the [`partial_cmp`] method, with the others
830 /// generated from default implementations.
832 /// However it remains possible to implement the others separately for types which do not have a
833 /// total order. For example, for floating point numbers, `NaN < 0 == false` and `NaN >= 0 ==
834 /// false` (cf. IEEE 754-2008 section 5.11).
836 /// `PartialOrd` requires your type to be [`PartialEq`].
838 /// Implementations of [`PartialEq`], `PartialOrd`, and [`Ord`] *must* agree with each other. It's
839 /// easy to accidentally make them disagree by deriving some of the traits and manually
840 /// implementing others.
842 /// If your type is [`Ord`], you can implement [`partial_cmp`] by using [`cmp`]:
845 /// use std::cmp::Ordering;
854 /// impl PartialOrd for Person {
855 /// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
856 /// Some(self.cmp(other))
860 /// impl Ord for Person {
861 /// fn cmp(&self, other: &Self) -> Ordering {
862 /// self.height.cmp(&other.height)
866 /// impl PartialEq for Person {
867 /// fn eq(&self, other: &Self) -> bool {
868 /// self.height == other.height
873 /// You may also find it useful to use [`partial_cmp`] on your type's fields. Here
874 /// is an example of `Person` types who have a floating-point `height` field that
875 /// is the only field to be used for sorting:
878 /// use std::cmp::Ordering;
886 /// impl PartialOrd for Person {
887 /// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
888 /// self.height.partial_cmp(&other.height)
892 /// impl PartialEq for Person {
893 /// fn eq(&self, other: &Self) -> bool {
894 /// self.height == other.height
905 /// assert_eq!(x < y, true);
906 /// assert_eq!(x.lt(&y), true);
909 /// [`partial_cmp`]: PartialOrd::partial_cmp
910 /// [`cmp`]: Ord::cmp
911 #[lang = "partial_ord"]
912 #[stable(feature = "rust1", since = "1.0.0")]
917 #[rustc_on_unimplemented(
918 message
= "can't compare `{Self}` with `{Rhs}`",
919 label
= "no implementation for `{Self} < {Rhs}` and `{Self} > {Rhs}`"
921 pub trait PartialOrd
<Rhs
: ?Sized
= Self>: PartialEq
<Rhs
> {
922 /// This method returns an ordering between `self` and `other` values if one exists.
927 /// use std::cmp::Ordering;
929 /// let result = 1.0.partial_cmp(&2.0);
930 /// assert_eq!(result, Some(Ordering::Less));
932 /// let result = 1.0.partial_cmp(&1.0);
933 /// assert_eq!(result, Some(Ordering::Equal));
935 /// let result = 2.0.partial_cmp(&1.0);
936 /// assert_eq!(result, Some(Ordering::Greater));
939 /// When comparison is impossible:
942 /// let result = f64::NAN.partial_cmp(&1.0);
943 /// assert_eq!(result, None);
946 #[stable(feature = "rust1", since = "1.0.0")]
947 fn partial_cmp(&self, other
: &Rhs
) -> Option
<Ordering
>;
949 /// This method tests less than (for `self` and `other`) and is used by the `<` operator.
954 /// let result = 1.0 < 2.0;
955 /// assert_eq!(result, true);
957 /// let result = 2.0 < 1.0;
958 /// assert_eq!(result, false);
962 #[stable(feature = "rust1", since = "1.0.0")]
963 fn lt(&self, other
: &Rhs
) -> bool
{
964 matches
!(self.partial_cmp(other
), Some(Less
))
967 /// This method tests less than or equal to (for `self` and `other`) and is used by the `<=`
973 /// let result = 1.0 <= 2.0;
974 /// assert_eq!(result, true);
976 /// let result = 2.0 <= 2.0;
977 /// assert_eq!(result, true);
981 #[stable(feature = "rust1", since = "1.0.0")]
982 fn le(&self, other
: &Rhs
) -> bool
{
983 matches
!(self.partial_cmp(other
), Some(Less
| Equal
))
986 /// This method tests greater than (for `self` and `other`) and is used by the `>` operator.
991 /// let result = 1.0 > 2.0;
992 /// assert_eq!(result, false);
994 /// let result = 2.0 > 2.0;
995 /// assert_eq!(result, false);
999 #[stable(feature = "rust1", since = "1.0.0")]
1000 fn gt(&self, other
: &Rhs
) -> bool
{
1001 matches
!(self.partial_cmp(other
), Some(Greater
))
1004 /// This method tests greater than or equal to (for `self` and `other`) and is used by the `>=`
1010 /// let result = 2.0 >= 1.0;
1011 /// assert_eq!(result, true);
1013 /// let result = 2.0 >= 2.0;
1014 /// assert_eq!(result, true);
1018 #[stable(feature = "rust1", since = "1.0.0")]
1019 fn ge(&self, other
: &Rhs
) -> bool
{
1020 matches
!(self.partial_cmp(other
), Some(Greater
| Equal
))
1024 /// Derive macro generating an impl of the trait `PartialOrd`.
1025 #[rustc_builtin_macro]
1026 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
1027 #[allow_internal_unstable(core_intrinsics)]
1028 pub macro PartialOrd($item
:item
) {
1029 /* compiler built-in */
1032 /// Compares and returns the minimum of two values.
1034 /// Returns the first argument if the comparison determines them to be equal.
1036 /// Internally uses an alias to [`Ord::min`].
1043 /// assert_eq!(1, cmp::min(1, 2));
1044 /// assert_eq!(2, cmp::min(2, 2));
1048 #[stable(feature = "rust1", since = "1.0.0")]
1049 pub fn min
<T
: Ord
>(v1
: T
, v2
: T
) -> T
{
1053 /// Returns the minimum of two values with respect to the specified comparison function.
1055 /// Returns the first argument if the comparison determines them to be equal.
1060 /// #![feature(cmp_min_max_by)]
1064 /// assert_eq!(cmp::min_by(-2, 1, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), 1);
1065 /// assert_eq!(cmp::min_by(-2, 2, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), -2);
1069 #[unstable(feature = "cmp_min_max_by", issue = "64460")]
1070 pub fn min_by
<T
, F
: FnOnce(&T
, &T
) -> Ordering
>(v1
: T
, v2
: T
, compare
: F
) -> T
{
1071 match compare(&v1
, &v2
) {
1072 Ordering
::Less
| Ordering
::Equal
=> v1
,
1073 Ordering
::Greater
=> v2
,
1077 /// Returns the element that gives the minimum value from the specified function.
1079 /// Returns the first argument if the comparison determines them to be equal.
1084 /// #![feature(cmp_min_max_by)]
1088 /// assert_eq!(cmp::min_by_key(-2, 1, |x: &i32| x.abs()), 1);
1089 /// assert_eq!(cmp::min_by_key(-2, 2, |x: &i32| x.abs()), -2);
1093 #[unstable(feature = "cmp_min_max_by", issue = "64460")]
1094 pub fn min_by_key
<T
, F
: FnMut(&T
) -> K
, K
: Ord
>(v1
: T
, v2
: T
, mut f
: F
) -> T
{
1095 min_by(v1
, v2
, |v1
, v2
| f(v1
).cmp(&f(v2
)))
1098 /// Compares and returns the maximum of two values.
1100 /// Returns the second argument if the comparison determines them to be equal.
1102 /// Internally uses an alias to [`Ord::max`].
1109 /// assert_eq!(2, cmp::max(1, 2));
1110 /// assert_eq!(2, cmp::max(2, 2));
1114 #[stable(feature = "rust1", since = "1.0.0")]
1115 pub fn max
<T
: Ord
>(v1
: T
, v2
: T
) -> T
{
1119 /// Returns the maximum of two values with respect to the specified comparison function.
1121 /// Returns the second argument if the comparison determines them to be equal.
1126 /// #![feature(cmp_min_max_by)]
1130 /// assert_eq!(cmp::max_by(-2, 1, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), -2);
1131 /// assert_eq!(cmp::max_by(-2, 2, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), 2);
1135 #[unstable(feature = "cmp_min_max_by", issue = "64460")]
1136 pub fn max_by
<T
, F
: FnOnce(&T
, &T
) -> Ordering
>(v1
: T
, v2
: T
, compare
: F
) -> T
{
1137 match compare(&v1
, &v2
) {
1138 Ordering
::Less
| Ordering
::Equal
=> v2
,
1139 Ordering
::Greater
=> v1
,
1143 /// Returns the element that gives the maximum value from the specified function.
1145 /// Returns the second argument if the comparison determines them to be equal.
1150 /// #![feature(cmp_min_max_by)]
1154 /// assert_eq!(cmp::max_by_key(-2, 1, |x: &i32| x.abs()), -2);
1155 /// assert_eq!(cmp::max_by_key(-2, 2, |x: &i32| x.abs()), 2);
1159 #[unstable(feature = "cmp_min_max_by", issue = "64460")]
1160 pub fn max_by_key
<T
, F
: FnMut(&T
) -> K
, K
: Ord
>(v1
: T
, v2
: T
, mut f
: F
) -> T
{
1161 max_by(v1
, v2
, |v1
, v2
| f(v1
).cmp(&f(v2
)))
1164 // Implementation of PartialEq, Eq, PartialOrd and Ord for primitive types
1166 use crate::cmp
::Ordering
::{self, Equal, Greater, Less}
;
1167 use crate::hint
::unreachable_unchecked
;
1169 macro_rules
! partial_eq_impl
{
1171 #[stable(feature = "rust1", since = "1.0.0")]
1172 impl PartialEq
for $t
{
1174 fn eq(&self, other
: &$t
) -> bool { (*self) == (*other) }
1176 fn ne(&self, other
: &$t
) -> bool { (*self) != (*other) }
1181 #[stable(feature = "rust1", since = "1.0.0")]
1182 impl PartialEq
for () {
1184 fn eq(&self, _other
: &()) -> bool
{
1188 fn ne(&self, _other
: &()) -> bool
{
1194 bool
char usize u8 u16 u32 u64 u128
isize i8 i16 i32 i64 i128
f32 f64
1197 macro_rules
! eq_impl
{
1199 #[stable(feature = "rust1", since = "1.0.0")]
1204 eq_impl
! { () bool char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1206 macro_rules
! partial_ord_impl
{
1208 #[stable(feature = "rust1", since = "1.0.0")]
1209 impl PartialOrd
for $t
{
1211 fn partial_cmp(&self, other
: &$t
) -> Option
<Ordering
> {
1212 match (self <= other
, self >= other
) {
1213 (false, false) => None
,
1214 (false, true) => Some(Greater
),
1215 (true, false) => Some(Less
),
1216 (true, true) => Some(Equal
),
1220 fn lt(&self, other
: &$t
) -> bool { (*self) < (*other) }
1222 fn le(&self, other
: &$t
) -> bool { (*self) <= (*other) }
1224 fn ge(&self, other
: &$t
) -> bool { (*self) >= (*other) }
1226 fn gt(&self, other
: &$t
) -> bool { (*self) > (*other) }
1231 #[stable(feature = "rust1", since = "1.0.0")]
1232 impl PartialOrd
for () {
1234 fn partial_cmp(&self, _
: &()) -> Option
<Ordering
> {
1239 #[stable(feature = "rust1", since = "1.0.0")]
1240 impl PartialOrd
for bool
{
1242 fn partial_cmp(&self, other
: &bool
) -> Option
<Ordering
> {
1243 Some(self.cmp(other
))
1247 partial_ord_impl
! { f32 f64 }
1249 macro_rules
! ord_impl
{
1251 #[stable(feature = "rust1", since = "1.0.0")]
1252 impl PartialOrd
for $t
{
1254 fn partial_cmp(&self, other
: &$t
) -> Option
<Ordering
> {
1255 Some(self.cmp(other
))
1258 fn lt(&self, other
: &$t
) -> bool { (*self) < (*other) }
1260 fn le(&self, other
: &$t
) -> bool { (*self) <= (*other) }
1262 fn ge(&self, other
: &$t
) -> bool { (*self) >= (*other) }
1264 fn gt(&self, other
: &$t
) -> bool { (*self) > (*other) }
1267 #[stable(feature = "rust1", since = "1.0.0")]
1270 fn cmp(&self, other
: &$t
) -> Ordering
{
1271 // The order here is important to generate more optimal assembly.
1272 // See <https://github.com/rust-lang/rust/issues/63758> for more info.
1273 if *self < *other { Less }
1274 else if *self == *other { Equal }
1281 #[stable(feature = "rust1", since = "1.0.0")]
1284 fn cmp(&self, _other
: &()) -> Ordering
{
1289 #[stable(feature = "rust1", since = "1.0.0")]
1292 fn cmp(&self, other
: &bool
) -> Ordering
{
1293 // Casting to i8's and converting the difference to an Ordering generates
1294 // more optimal assembly.
1295 // See <https://github.com/rust-lang/rust/issues/66780> for more info.
1296 match (*self as i8) - (*other
as i8) {
1300 // SAFETY: bool as i8 returns 0 or 1, so the difference can't be anything else
1301 _
=> unsafe { unreachable_unchecked() }
,
1306 ord_impl
! { char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1308 #[unstable(feature = "never_type", issue = "35121")]
1309 impl PartialEq
for ! {
1310 fn eq(&self, _
: &!) -> bool
{
1315 #[unstable(feature = "never_type", issue = "35121")]
1318 #[unstable(feature = "never_type", issue = "35121")]
1319 impl PartialOrd
for ! {
1320 fn partial_cmp(&self, _
: &!) -> Option
<Ordering
> {
1325 #[unstable(feature = "never_type", issue = "35121")]
1327 fn cmp(&self, _
: &!) -> Ordering
{
1334 #[stable(feature = "rust1", since = "1.0.0")]
1335 impl<A
: ?Sized
, B
: ?Sized
> PartialEq
<&B
> for &A
1340 fn eq(&self, other
: &&B
) -> bool
{
1341 PartialEq
::eq(*self, *other
)
1344 fn ne(&self, other
: &&B
) -> bool
{
1345 PartialEq
::ne(*self, *other
)
1348 #[stable(feature = "rust1", since = "1.0.0")]
1349 impl<A
: ?Sized
, B
: ?Sized
> PartialOrd
<&B
> for &A
1354 fn partial_cmp(&self, other
: &&B
) -> Option
<Ordering
> {
1355 PartialOrd
::partial_cmp(*self, *other
)
1358 fn lt(&self, other
: &&B
) -> bool
{
1359 PartialOrd
::lt(*self, *other
)
1362 fn le(&self, other
: &&B
) -> bool
{
1363 PartialOrd
::le(*self, *other
)
1366 fn gt(&self, other
: &&B
) -> bool
{
1367 PartialOrd
::gt(*self, *other
)
1370 fn ge(&self, other
: &&B
) -> bool
{
1371 PartialOrd
::ge(*self, *other
)
1374 #[stable(feature = "rust1", since = "1.0.0")]
1375 impl<A
: ?Sized
> Ord
for &A
1380 fn cmp(&self, other
: &Self) -> Ordering
{
1381 Ord
::cmp(*self, *other
)
1384 #[stable(feature = "rust1", since = "1.0.0")]
1385 impl<A
: ?Sized
> Eq
for &A
where A
: Eq {}
1389 #[stable(feature = "rust1", since = "1.0.0")]
1390 impl<A
: ?Sized
, B
: ?Sized
> PartialEq
<&mut B
> for &mut A
1395 fn eq(&self, other
: &&mut B
) -> bool
{
1396 PartialEq
::eq(*self, *other
)
1399 fn ne(&self, other
: &&mut B
) -> bool
{
1400 PartialEq
::ne(*self, *other
)
1403 #[stable(feature = "rust1", since = "1.0.0")]
1404 impl<A
: ?Sized
, B
: ?Sized
> PartialOrd
<&mut B
> for &mut A
1409 fn partial_cmp(&self, other
: &&mut B
) -> Option
<Ordering
> {
1410 PartialOrd
::partial_cmp(*self, *other
)
1413 fn lt(&self, other
: &&mut B
) -> bool
{
1414 PartialOrd
::lt(*self, *other
)
1417 fn le(&self, other
: &&mut B
) -> bool
{
1418 PartialOrd
::le(*self, *other
)
1421 fn gt(&self, other
: &&mut B
) -> bool
{
1422 PartialOrd
::gt(*self, *other
)
1425 fn ge(&self, other
: &&mut B
) -> bool
{
1426 PartialOrd
::ge(*self, *other
)
1429 #[stable(feature = "rust1", since = "1.0.0")]
1430 impl<A
: ?Sized
> Ord
for &mut A
1435 fn cmp(&self, other
: &Self) -> Ordering
{
1436 Ord
::cmp(*self, *other
)
1439 #[stable(feature = "rust1", since = "1.0.0")]
1440 impl<A
: ?Sized
> Eq
for &mut A
where A
: Eq {}
1442 #[stable(feature = "rust1", since = "1.0.0")]
1443 impl<A
: ?Sized
, B
: ?Sized
> PartialEq
<&mut B
> for &A
1448 fn eq(&self, other
: &&mut B
) -> bool
{
1449 PartialEq
::eq(*self, *other
)
1452 fn ne(&self, other
: &&mut B
) -> bool
{
1453 PartialEq
::ne(*self, *other
)
1457 #[stable(feature = "rust1", since = "1.0.0")]
1458 impl<A
: ?Sized
, B
: ?Sized
> PartialEq
<&B
> for &mut A
1463 fn eq(&self, other
: &&B
) -> bool
{
1464 PartialEq
::eq(*self, *other
)
1467 fn ne(&self, other
: &&B
) -> bool
{
1468 PartialEq
::ne(*self, *other
)