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 [`Eq`].
34 /// Formally, the equality must be (for all `a`, `b` and `c`):
36 /// - symmetric: `a == b` implies `b == a`; and
37 /// - transitive: `a == b` and `b == c` implies `a == c`.
39 /// Note that these requirements mean that the trait itself must be implemented
40 /// symmetrically and transitively: if `T: PartialEq<U>` and `U: PartialEq<V>`
41 /// then `U: PartialEq<T>` and `T: PartialEq<V>`.
45 /// This trait can be used with `#[derive]`. When `derive`d on structs, two
46 /// instances are equal if all fields are equal, and not equal if any fields
47 /// are not equal. When `derive`d on enums, each variant is equal to itself
48 /// and not equal to the other variants.
50 /// ## How can I implement `PartialEq`?
52 /// `PartialEq` only requires the [`eq`] method to be implemented; [`ne`] is defined
53 /// in terms of it by default. Any manual implementation of [`ne`] *must* respect
54 /// the rule that [`eq`] is a strict inverse of [`ne`]; that is, `!(a == b)` if and
57 /// Implementations of `PartialEq`, [`PartialOrd`], and [`Ord`] *must* agree with
58 /// each other. It's easy to accidentally make them disagree by deriving some
59 /// of the traits and manually implementing others.
61 /// An example implementation for a domain in which two books are considered
62 /// the same book if their ISBN matches, even if the formats differ:
73 /// format: BookFormat,
76 /// impl PartialEq for Book {
77 /// fn eq(&self, other: &Self) -> bool {
78 /// self.isbn == other.isbn
82 /// let b1 = Book { isbn: 3, format: BookFormat::Paperback };
83 /// let b2 = Book { isbn: 3, format: BookFormat::Ebook };
84 /// let b3 = Book { isbn: 10, format: BookFormat::Paperback };
86 /// assert!(b1 == b2);
87 /// assert!(b1 != b3);
90 /// ## How can I compare two different types?
92 /// The type you can compare with is controlled by `PartialEq`'s type parameter.
93 /// For example, let's tweak our previous code a bit:
96 /// // The derive implements <BookFormat> == <BookFormat> comparisons
97 /// #[derive(PartialEq)]
106 /// format: BookFormat,
109 /// // Implement <Book> == <BookFormat> comparisons
110 /// impl PartialEq<BookFormat> for Book {
111 /// fn eq(&self, other: &BookFormat) -> bool {
112 /// self.format == *other
116 /// // Implement <BookFormat> == <Book> comparisons
117 /// impl PartialEq<Book> for BookFormat {
118 /// fn eq(&self, other: &Book) -> bool {
119 /// *self == other.format
123 /// let b1 = Book { isbn: 3, format: BookFormat::Paperback };
125 /// assert!(b1 == BookFormat::Paperback);
126 /// assert!(BookFormat::Ebook != b1);
129 /// By changing `impl PartialEq for Book` to `impl PartialEq<BookFormat> for Book`,
130 /// we allow `BookFormat`s to be compared with `Book`s.
132 /// A comparison like the one above, which ignores some fields of the struct,
133 /// can be dangerous. It can easily lead to an unintended violation of the
134 /// requirements for a partial equivalence relation. For example, if we kept
135 /// the above implementation of `PartialEq<Book>` for `BookFormat` and added an
136 /// implementation of `PartialEq<Book>` for `Book` (either via a `#[derive]` or
137 /// via the manual implementation from the first example) then the result would
138 /// violate transitivity:
141 /// #[derive(PartialEq)]
142 /// enum BookFormat {
148 /// #[derive(PartialEq)]
151 /// format: BookFormat,
154 /// impl PartialEq<BookFormat> for Book {
155 /// fn eq(&self, other: &BookFormat) -> bool {
156 /// self.format == *other
160 /// impl PartialEq<Book> for BookFormat {
161 /// fn eq(&self, other: &Book) -> bool {
162 /// *self == other.format
167 /// let b1 = Book { isbn: 1, format: BookFormat::Paperback };
168 /// let b2 = Book { isbn: 2, format: BookFormat::Paperback };
170 /// assert!(b1 == BookFormat::Paperback);
171 /// assert!(BookFormat::Paperback == b2);
173 /// // The following should hold by transitivity but doesn't.
174 /// assert!(b1 == b2); // <-- PANICS
184 /// assert_eq!(x == y, false);
185 /// assert_eq!(x.eq(&y), false);
188 /// [`eq`]: PartialEq::eq
189 /// [`ne`]: PartialEq::ne
191 #[stable(feature = "rust1", since = "1.0.0")]
194 #[rustc_on_unimplemented(
195 message = "can't compare `{Self}` with `{Rhs}`",
196 label = "no implementation for `{Self} == {Rhs}`"
198 pub trait PartialEq<Rhs: ?Sized = Self> {
199 /// This method tests for `self` and `other` values to be equal, and is used
202 #[stable(feature = "rust1", since = "1.0.0")]
203 fn eq(&self, other: &Rhs) -> bool;
205 /// This method tests for `!=`.
208 #[stable(feature = "rust1", since = "1.0.0")]
209 fn ne(&self, other: &Rhs) -> bool {
214 /// Derive macro generating an impl of the trait `PartialEq`.
215 #[rustc_builtin_macro]
216 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
217 #[allow_internal_unstable(core_intrinsics, structural_match)]
218 pub macro PartialEq($item:item) {
219 /* compiler built-in */
222 /// Trait for equality comparisons which are [equivalence relations](
223 /// https://en.wikipedia.org/wiki/Equivalence_relation).
225 /// This means, that in addition to `a == b` and `a != b` being strict inverses, the equality must
226 /// be (for all `a`, `b` and `c`):
228 /// - reflexive: `a == a`;
229 /// - symmetric: `a == b` implies `b == a`; and
230 /// - transitive: `a == b` and `b == c` implies `a == c`.
232 /// This property cannot be checked by the compiler, and therefore `Eq` implies
233 /// [`PartialEq`], and has no extra methods.
237 /// This trait can be used with `#[derive]`. When `derive`d, because `Eq` has
238 /// no extra methods, it is only informing the compiler that this is an
239 /// equivalence relation rather than a partial equivalence relation. Note that
240 /// the `derive` strategy requires all fields are `Eq`, which isn't
243 /// ## How can I implement `Eq`?
245 /// If you cannot use the `derive` strategy, specify that your type implements
246 /// `Eq`, which has no methods:
249 /// enum BookFormat { Paperback, Hardback, Ebook }
252 /// format: BookFormat,
254 /// impl PartialEq for Book {
255 /// fn eq(&self, other: &Self) -> bool {
256 /// self.isbn == other.isbn
259 /// impl Eq for Book {}
263 #[stable(feature = "rust1", since = "1.0.0")]
264 pub trait Eq: PartialEq<Self> {
265 // this method is used solely by #[deriving] to assert
266 // that every component of a type implements #[deriving]
267 // itself, the current deriving infrastructure means doing this
268 // assertion without using a method on this trait is nearly
271 // This should never be implemented by hand.
274 #[stable(feature = "rust1", since = "1.0.0")]
275 fn assert_receiver_is_total_eq(&self) {}
278 /// Derive macro generating an impl of the trait `Eq`.
279 #[rustc_builtin_macro]
280 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
281 #[allow_internal_unstable(core_intrinsics, derive_eq, structural_match)]
282 pub macro Eq($item:item) {
283 /* compiler built-in */
286 // FIXME: this struct is used solely by #[derive] to
287 // assert that every component of a type implements Eq.
289 // This struct should never appear in user code.
291 #[allow(missing_debug_implementations)]
292 #[unstable(feature = "derive_eq", reason = "deriving hack, should not be public", issue = "none")]
293 pub struct AssertParamIsEq<T: Eq + ?Sized> {
294 _field: crate::marker::PhantomData<T>,
297 /// An `Ordering` is the result of a comparison between two values.
302 /// use std::cmp::Ordering;
304 /// let result = 1.cmp(&2);
305 /// assert_eq!(Ordering::Less, result);
307 /// let result = 1.cmp(&1);
308 /// assert_eq!(Ordering::Equal, result);
310 /// let result = 2.cmp(&1);
311 /// assert_eq!(Ordering::Greater, result);
313 #[derive(Clone, Copy, PartialEq, Debug, Hash)]
314 #[stable(feature = "rust1", since = "1.0.0")]
316 /// An ordering where a compared value is less than another.
317 #[stable(feature = "rust1", since = "1.0.0")]
319 /// An ordering where a compared value is equal to another.
320 #[stable(feature = "rust1", since = "1.0.0")]
322 /// An ordering where a compared value is greater than another.
323 #[stable(feature = "rust1", since = "1.0.0")]
328 /// Returns `true` if the ordering is the `Equal` variant.
333 /// #![feature(ordering_helpers)]
334 /// use std::cmp::Ordering;
336 /// assert_eq!(Ordering::Less.is_eq(), false);
337 /// assert_eq!(Ordering::Equal.is_eq(), true);
338 /// assert_eq!(Ordering::Greater.is_eq(), false);
342 #[unstable(feature = "ordering_helpers", issue = "79885")]
343 pub const fn is_eq(self) -> bool {
344 matches!(self, Equal)
347 /// Returns `true` if the ordering is not the `Equal` variant.
352 /// #![feature(ordering_helpers)]
353 /// use std::cmp::Ordering;
355 /// assert_eq!(Ordering::Less.is_ne(), true);
356 /// assert_eq!(Ordering::Equal.is_ne(), false);
357 /// assert_eq!(Ordering::Greater.is_ne(), true);
361 #[unstable(feature = "ordering_helpers", issue = "79885")]
362 pub const fn is_ne(self) -> bool {
363 !matches!(self, Equal)
366 /// Returns `true` if the ordering is the `Less` variant.
371 /// #![feature(ordering_helpers)]
372 /// use std::cmp::Ordering;
374 /// assert_eq!(Ordering::Less.is_lt(), true);
375 /// assert_eq!(Ordering::Equal.is_lt(), false);
376 /// assert_eq!(Ordering::Greater.is_lt(), false);
380 #[unstable(feature = "ordering_helpers", issue = "79885")]
381 pub const fn is_lt(self) -> bool {
385 /// Returns `true` if the ordering is the `Greater` variant.
390 /// #![feature(ordering_helpers)]
391 /// use std::cmp::Ordering;
393 /// assert_eq!(Ordering::Less.is_gt(), false);
394 /// assert_eq!(Ordering::Equal.is_gt(), false);
395 /// assert_eq!(Ordering::Greater.is_gt(), true);
399 #[unstable(feature = "ordering_helpers", issue = "79885")]
400 pub const fn is_gt(self) -> bool {
401 matches!(self, Greater)
404 /// Returns `true` if the ordering is either the `Less` or `Equal` variant.
409 /// #![feature(ordering_helpers)]
410 /// use std::cmp::Ordering;
412 /// assert_eq!(Ordering::Less.is_le(), true);
413 /// assert_eq!(Ordering::Equal.is_le(), true);
414 /// assert_eq!(Ordering::Greater.is_le(), false);
418 #[unstable(feature = "ordering_helpers", issue = "79885")]
419 pub const fn is_le(self) -> bool {
420 !matches!(self, Greater)
423 /// Returns `true` if the ordering is either the `Greater` or `Equal` variant.
428 /// #![feature(ordering_helpers)]
429 /// use std::cmp::Ordering;
431 /// assert_eq!(Ordering::Less.is_ge(), false);
432 /// assert_eq!(Ordering::Equal.is_ge(), true);
433 /// assert_eq!(Ordering::Greater.is_ge(), true);
437 #[unstable(feature = "ordering_helpers", issue = "79885")]
438 pub const fn is_ge(self) -> bool {
439 !matches!(self, Less)
442 /// Reverses the `Ordering`.
444 /// * `Less` becomes `Greater`.
445 /// * `Greater` becomes `Less`.
446 /// * `Equal` becomes `Equal`.
453 /// use std::cmp::Ordering;
455 /// assert_eq!(Ordering::Less.reverse(), Ordering::Greater);
456 /// assert_eq!(Ordering::Equal.reverse(), Ordering::Equal);
457 /// assert_eq!(Ordering::Greater.reverse(), Ordering::Less);
460 /// This method can be used to reverse a comparison:
463 /// let data: &mut [_] = &mut [2, 10, 5, 8];
465 /// // sort the array from largest to smallest.
466 /// data.sort_by(|a, b| a.cmp(b).reverse());
468 /// let b: &mut [_] = &mut [10, 8, 5, 2];
469 /// assert!(data == b);
473 #[rustc_const_stable(feature = "const_ordering", since = "1.48.0")]
474 #[stable(feature = "rust1", since = "1.0.0")]
475 pub const fn reverse(self) -> Ordering {
483 /// Chains two orderings.
485 /// Returns `self` when it's not `Equal`. Otherwise returns `other`.
490 /// use std::cmp::Ordering;
492 /// let result = Ordering::Equal.then(Ordering::Less);
493 /// assert_eq!(result, Ordering::Less);
495 /// let result = Ordering::Less.then(Ordering::Equal);
496 /// assert_eq!(result, Ordering::Less);
498 /// let result = Ordering::Less.then(Ordering::Greater);
499 /// assert_eq!(result, Ordering::Less);
501 /// let result = Ordering::Equal.then(Ordering::Equal);
502 /// assert_eq!(result, Ordering::Equal);
504 /// let x: (i64, i64, i64) = (1, 2, 7);
505 /// let y: (i64, i64, i64) = (1, 5, 3);
506 /// let result = x.0.cmp(&y.0).then(x.1.cmp(&y.1)).then(x.2.cmp(&y.2));
508 /// assert_eq!(result, Ordering::Less);
512 #[rustc_const_stable(feature = "const_ordering", since = "1.48.0")]
513 #[stable(feature = "ordering_chaining", since = "1.17.0")]
514 pub const fn then(self, other: Ordering) -> Ordering {
521 /// Chains the ordering with the given function.
523 /// Returns `self` when it's not `Equal`. Otherwise calls `f` and returns
529 /// use std::cmp::Ordering;
531 /// let result = Ordering::Equal.then_with(|| Ordering::Less);
532 /// assert_eq!(result, Ordering::Less);
534 /// let result = Ordering::Less.then_with(|| Ordering::Equal);
535 /// assert_eq!(result, Ordering::Less);
537 /// let result = Ordering::Less.then_with(|| Ordering::Greater);
538 /// assert_eq!(result, Ordering::Less);
540 /// let result = Ordering::Equal.then_with(|| Ordering::Equal);
541 /// assert_eq!(result, Ordering::Equal);
543 /// let x: (i64, i64, i64) = (1, 2, 7);
544 /// let y: (i64, i64, i64) = (1, 5, 3);
545 /// let result = x.0.cmp(&y.0).then_with(|| x.1.cmp(&y.1)).then_with(|| x.2.cmp(&y.2));
547 /// assert_eq!(result, Ordering::Less);
551 #[stable(feature = "ordering_chaining", since = "1.17.0")]
552 pub fn then_with<F: FnOnce() -> Ordering>(self, f: F) -> Ordering {
560 /// A helper struct for reverse ordering.
562 /// This struct is a helper to be used with functions like [`Vec::sort_by_key`] and
563 /// can be used to reverse order a part of a key.
565 /// [`Vec::sort_by_key`]: ../../std/vec/struct.Vec.html#method.sort_by_key
570 /// use std::cmp::Reverse;
572 /// let mut v = vec![1, 2, 3, 4, 5, 6];
573 /// v.sort_by_key(|&num| (num > 3, Reverse(num)));
574 /// assert_eq!(v, vec![3, 2, 1, 6, 5, 4]);
576 #[derive(PartialEq, Eq, Debug, Copy, Clone, Default, Hash)]
577 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
578 pub struct Reverse<T>(#[stable(feature = "reverse_cmp_key", since = "1.19.0")] pub T);
580 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
581 impl<T: PartialOrd> PartialOrd for Reverse<T> {
583 fn partial_cmp(&self, other: &Reverse<T>) -> Option<Ordering> {
584 other.0.partial_cmp(&self.0)
588 fn lt(&self, other: &Self) -> bool {
592 fn le(&self, other: &Self) -> bool {
596 fn gt(&self, other: &Self) -> bool {
600 fn ge(&self, other: &Self) -> bool {
605 #[stable(feature = "reverse_cmp_key", since = "1.19.0")]
606 impl<T: Ord> Ord for Reverse<T> {
608 fn cmp(&self, other: &Reverse<T>) -> Ordering {
613 /// Trait for types that form a [total order](https://en.wikipedia.org/wiki/Total_order).
615 /// An order is a total order if it is (for all `a`, `b` and `c`):
617 /// - total and asymmetric: exactly one of `a < b`, `a == b` or `a > b` is true; and
618 /// - transitive, `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
622 /// This trait can be used with `#[derive]`. When `derive`d on structs, it will produce a
623 /// [lexicographic](https://en.wikipedia.org/wiki/Lexicographic_order) ordering based on the top-to-bottom declaration order of the struct's members.
624 /// When `derive`d on enums, variants are ordered by their top-to-bottom discriminant order.
626 /// ## Lexicographical comparison
628 /// Lexicographical comparison is an operation with the following properties:
629 /// - Two sequences are compared element by element.
630 /// - The first mismatching element defines which sequence is lexicographically less or greater than the other.
631 /// - If one sequence is a prefix of another, the shorter sequence is lexicographically less than the other.
632 /// - If two sequence have equivalent elements and are of the same length, then the sequences are lexicographically equal.
633 /// - An empty sequence is lexicographically less than any non-empty sequence.
634 /// - Two empty sequences are lexicographically equal.
636 /// ## How can I implement `Ord`?
638 /// `Ord` requires that the type also be [`PartialOrd`] and [`Eq`] (which requires [`PartialEq`]).
640 /// Then you must define an implementation for [`cmp`]. You may find it useful to use
641 /// [`cmp`] on your type's fields.
643 /// Implementations of [`PartialEq`], [`PartialOrd`], and `Ord` *must*
644 /// agree with each other. That is, `a.cmp(b) == Ordering::Equal` if
645 /// and only if `a == b` and `Some(a.cmp(b)) == a.partial_cmp(b)` for
646 /// all `a` and `b`. It's easy to accidentally make them disagree by
647 /// deriving some of the traits and manually implementing others.
649 /// Here's an example where you want to sort people by height only, disregarding `id`
653 /// use std::cmp::Ordering;
662 /// impl Ord for Person {
663 /// fn cmp(&self, other: &Self) -> Ordering {
664 /// self.height.cmp(&other.height)
668 /// impl PartialOrd for Person {
669 /// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
670 /// Some(self.cmp(other))
674 /// impl PartialEq for Person {
675 /// fn eq(&self, other: &Self) -> bool {
676 /// self.height == other.height
681 /// [`cmp`]: Ord::cmp
686 #[stable(feature = "rust1", since = "1.0.0")]
687 pub trait Ord: Eq + PartialOrd<Self> {
688 /// This method returns an [`Ordering`] between `self` and `other`.
690 /// By convention, `self.cmp(&other)` returns the ordering matching the expression
691 /// `self <operator> other` if true.
696 /// use std::cmp::Ordering;
698 /// assert_eq!(5.cmp(&10), Ordering::Less);
699 /// assert_eq!(10.cmp(&5), Ordering::Greater);
700 /// assert_eq!(5.cmp(&5), Ordering::Equal);
703 #[stable(feature = "rust1", since = "1.0.0")]
704 fn cmp(&self, other: &Self) -> Ordering;
706 /// Compares and returns the maximum of two values.
708 /// Returns the second argument if the comparison determines them to be equal.
713 /// assert_eq!(2, 1.max(2));
714 /// assert_eq!(2, 2.max(2));
716 #[stable(feature = "ord_max_min", since = "1.21.0")]
719 fn max(self, other: Self) -> Self
723 max_by(self, other, Ord::cmp)
726 /// Compares and returns the minimum of two values.
728 /// Returns the first argument if the comparison determines them to be equal.
733 /// assert_eq!(1, 1.min(2));
734 /// assert_eq!(2, 2.min(2));
736 #[stable(feature = "ord_max_min", since = "1.21.0")]
739 fn min(self, other: Self) -> Self
743 min_by(self, other, Ord::cmp)
746 /// Restrict a value to a certain interval.
748 /// Returns `max` if `self` is greater than `max`, and `min` if `self` is
749 /// less than `min`. Otherwise this returns `self`.
753 /// Panics if `min > max`.
758 /// assert!((-3).clamp(-2, 1) == -2);
759 /// assert!(0.clamp(-2, 1) == 0);
760 /// assert!(2.clamp(-2, 1) == 1);
763 #[stable(feature = "clamp", since = "1.50.0")]
764 fn clamp(self, min: Self, max: Self) -> Self
771 } else if self > max {
779 /// Derive macro generating an impl of the trait `Ord`.
780 #[rustc_builtin_macro]
781 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
782 #[allow_internal_unstable(core_intrinsics)]
783 pub macro Ord($item:item) {
784 /* compiler built-in */
787 #[stable(feature = "rust1", since = "1.0.0")]
788 impl Eq for Ordering {}
790 #[stable(feature = "rust1", since = "1.0.0")]
791 impl Ord for Ordering {
793 fn cmp(&self, other: &Ordering) -> Ordering {
794 (*self as i32).cmp(&(*other as i32))
798 #[stable(feature = "rust1", since = "1.0.0")]
799 impl PartialOrd for Ordering {
801 fn partial_cmp(&self, other: &Ordering) -> Option<Ordering> {
802 (*self as i32).partial_cmp(&(*other as i32))
806 /// Trait for values that can be compared for a sort-order.
808 /// The comparison must satisfy, for all `a`, `b` and `c`:
810 /// - asymmetry: if `a < b` then `!(a > b)`, as well as `a > b` implying `!(a < b)`; and
811 /// - transitivity: `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
813 /// Note that these requirements mean that the trait itself must be implemented symmetrically and
814 /// transitively: if `T: PartialOrd<U>` and `U: PartialOrd<V>` then `U: PartialOrd<T>` and `T:
819 /// This trait can be used with `#[derive]`. When `derive`d on structs, it will produce a
820 /// lexicographic ordering based on the top-to-bottom declaration order of the struct's members.
821 /// When `derive`d on enums, variants are ordered by their top-to-bottom discriminant order.
823 /// ## How can I implement `PartialOrd`?
825 /// `PartialOrd` only requires implementation of the [`partial_cmp`] method, with the others
826 /// generated from default implementations.
828 /// However it remains possible to implement the others separately for types which do not have a
829 /// total order. For example, for floating point numbers, `NaN < 0 == false` and `NaN >= 0 ==
830 /// false` (cf. IEEE 754-2008 section 5.11).
832 /// `PartialOrd` requires your type to be [`PartialEq`].
834 /// Implementations of [`PartialEq`], `PartialOrd`, and [`Ord`] *must* agree with each other. It's
835 /// easy to accidentally make them disagree by deriving some of the traits and manually
836 /// implementing others.
838 /// If your type is [`Ord`], you can implement [`partial_cmp`] by using [`cmp`]:
841 /// use std::cmp::Ordering;
850 /// impl PartialOrd for Person {
851 /// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
852 /// Some(self.cmp(other))
856 /// impl Ord for Person {
857 /// fn cmp(&self, other: &Self) -> Ordering {
858 /// self.height.cmp(&other.height)
862 /// impl PartialEq for Person {
863 /// fn eq(&self, other: &Self) -> bool {
864 /// self.height == other.height
869 /// You may also find it useful to use [`partial_cmp`] on your type's fields. Here
870 /// is an example of `Person` types who have a floating-point `height` field that
871 /// is the only field to be used for sorting:
874 /// use std::cmp::Ordering;
882 /// impl PartialOrd for Person {
883 /// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
884 /// self.height.partial_cmp(&other.height)
888 /// impl PartialEq for Person {
889 /// fn eq(&self, other: &Self) -> bool {
890 /// self.height == other.height
901 /// assert_eq!(x < y, true);
902 /// assert_eq!(x.lt(&y), true);
905 /// [`partial_cmp`]: PartialOrd::partial_cmp
906 /// [`cmp`]: Ord::cmp
907 #[lang = "partial_ord"]
908 #[stable(feature = "rust1", since = "1.0.0")]
913 #[rustc_on_unimplemented(
914 message = "can't compare `{Self}` with `{Rhs}`",
915 label = "no implementation for `{Self} < {Rhs}` and `{Self} > {Rhs}`"
917 pub trait PartialOrd<Rhs: ?Sized = Self>: PartialEq<Rhs> {
918 /// This method returns an ordering between `self` and `other` values if one exists.
923 /// use std::cmp::Ordering;
925 /// let result = 1.0.partial_cmp(&2.0);
926 /// assert_eq!(result, Some(Ordering::Less));
928 /// let result = 1.0.partial_cmp(&1.0);
929 /// assert_eq!(result, Some(Ordering::Equal));
931 /// let result = 2.0.partial_cmp(&1.0);
932 /// assert_eq!(result, Some(Ordering::Greater));
935 /// When comparison is impossible:
938 /// let result = f64::NAN.partial_cmp(&1.0);
939 /// assert_eq!(result, None);
942 #[stable(feature = "rust1", since = "1.0.0")]
943 fn partial_cmp(&self, other: &Rhs) -> Option<Ordering>;
945 /// This method tests less than (for `self` and `other`) and is used by the `<` operator.
950 /// let result = 1.0 < 2.0;
951 /// assert_eq!(result, true);
953 /// let result = 2.0 < 1.0;
954 /// assert_eq!(result, false);
958 #[stable(feature = "rust1", since = "1.0.0")]
959 fn lt(&self, other: &Rhs) -> bool {
960 matches!(self.partial_cmp(other), Some(Less))
963 /// This method tests less than or equal to (for `self` and `other`) and is used by the `<=`
969 /// let result = 1.0 <= 2.0;
970 /// assert_eq!(result, true);
972 /// let result = 2.0 <= 2.0;
973 /// assert_eq!(result, true);
977 #[stable(feature = "rust1", since = "1.0.0")]
978 fn le(&self, other: &Rhs) -> bool {
979 matches!(self.partial_cmp(other), Some(Less | Equal))
982 /// This method tests greater than (for `self` and `other`) and is used by the `>` operator.
987 /// let result = 1.0 > 2.0;
988 /// assert_eq!(result, false);
990 /// let result = 2.0 > 2.0;
991 /// assert_eq!(result, false);
995 #[stable(feature = "rust1", since = "1.0.0")]
996 fn gt(&self, other: &Rhs) -> bool {
997 matches!(self.partial_cmp(other), Some(Greater))
1000 /// This method tests greater than or equal to (for `self` and `other`) and is used by the `>=`
1006 /// let result = 2.0 >= 1.0;
1007 /// assert_eq!(result, true);
1009 /// let result = 2.0 >= 2.0;
1010 /// assert_eq!(result, true);
1014 #[stable(feature = "rust1", since = "1.0.0")]
1015 fn ge(&self, other: &Rhs) -> bool {
1016 matches!(self.partial_cmp(other), Some(Greater | Equal))
1020 /// Derive macro generating an impl of the trait `PartialOrd`.
1021 #[rustc_builtin_macro]
1022 #[stable(feature = "builtin_macro_prelude", since = "1.38.0")]
1023 #[allow_internal_unstable(core_intrinsics)]
1024 pub macro PartialOrd($item:item) {
1025 /* compiler built-in */
1028 /// Compares and returns the minimum of two values.
1030 /// Returns the first argument if the comparison determines them to be equal.
1032 /// Internally uses an alias to [`Ord::min`].
1039 /// assert_eq!(1, cmp::min(1, 2));
1040 /// assert_eq!(2, cmp::min(2, 2));
1044 #[stable(feature = "rust1", since = "1.0.0")]
1045 pub fn min<T: Ord>(v1: T, v2: T) -> T {
1049 /// Returns the minimum of two values with respect to the specified comparison function.
1051 /// Returns the first argument if the comparison determines them to be equal.
1056 /// #![feature(cmp_min_max_by)]
1060 /// assert_eq!(cmp::min_by(-2, 1, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), 1);
1061 /// assert_eq!(cmp::min_by(-2, 2, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), -2);
1065 #[unstable(feature = "cmp_min_max_by", issue = "64460")]
1066 pub fn min_by<T, F: FnOnce(&T, &T) -> Ordering>(v1: T, v2: T, compare: F) -> T {
1067 match compare(&v1, &v2) {
1068 Ordering::Less | Ordering::Equal => v1,
1069 Ordering::Greater => v2,
1073 /// Returns the element that gives the minimum value from the specified function.
1075 /// Returns the first argument if the comparison determines them to be equal.
1080 /// #![feature(cmp_min_max_by)]
1084 /// assert_eq!(cmp::min_by_key(-2, 1, |x: &i32| x.abs()), 1);
1085 /// assert_eq!(cmp::min_by_key(-2, 2, |x: &i32| x.abs()), -2);
1089 #[unstable(feature = "cmp_min_max_by", issue = "64460")]
1090 pub fn min_by_key<T, F: FnMut(&T) -> K, K: Ord>(v1: T, v2: T, mut f: F) -> T {
1091 min_by(v1, v2, |v1, v2| f(v1).cmp(&f(v2)))
1094 /// Compares and returns the maximum of two values.
1096 /// Returns the second argument if the comparison determines them to be equal.
1098 /// Internally uses an alias to [`Ord::max`].
1105 /// assert_eq!(2, cmp::max(1, 2));
1106 /// assert_eq!(2, cmp::max(2, 2));
1110 #[stable(feature = "rust1", since = "1.0.0")]
1111 pub fn max<T: Ord>(v1: T, v2: T) -> T {
1115 /// Returns the maximum of two values with respect to the specified comparison function.
1117 /// Returns the second argument if the comparison determines them to be equal.
1122 /// #![feature(cmp_min_max_by)]
1126 /// assert_eq!(cmp::max_by(-2, 1, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), -2);
1127 /// assert_eq!(cmp::max_by(-2, 2, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), 2);
1131 #[unstable(feature = "cmp_min_max_by", issue = "64460")]
1132 pub fn max_by<T, F: FnOnce(&T, &T) -> Ordering>(v1: T, v2: T, compare: F) -> T {
1133 match compare(&v1, &v2) {
1134 Ordering::Less | Ordering::Equal => v2,
1135 Ordering::Greater => v1,
1139 /// Returns the element that gives the maximum value from the specified function.
1141 /// Returns the second argument if the comparison determines them to be equal.
1146 /// #![feature(cmp_min_max_by)]
1150 /// assert_eq!(cmp::max_by_key(-2, 1, |x: &i32| x.abs()), -2);
1151 /// assert_eq!(cmp::max_by_key(-2, 2, |x: &i32| x.abs()), 2);
1155 #[unstable(feature = "cmp_min_max_by", issue = "64460")]
1156 pub fn max_by_key<T, F: FnMut(&T) -> K, K: Ord>(v1: T, v2: T, mut f: F) -> T {
1157 max_by(v1, v2, |v1, v2| f(v1).cmp(&f(v2)))
1160 // Implementation of PartialEq, Eq, PartialOrd and Ord for primitive types
1162 use crate::cmp::Ordering::{self, Equal, Greater, Less};
1163 use crate::hint::unreachable_unchecked;
1165 macro_rules! partial_eq_impl {
1167 #[stable(feature = "rust1", since = "1.0.0")]
1168 impl PartialEq for $t {
1170 fn eq(&self, other: &$t) -> bool { (*self) == (*other) }
1172 fn ne(&self, other: &$t) -> bool { (*self) != (*other) }
1177 #[stable(feature = "rust1", since = "1.0.0")]
1178 impl PartialEq for () {
1180 fn eq(&self, _other: &()) -> bool {
1184 fn ne(&self, _other: &()) -> bool {
1190 bool char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64
1193 macro_rules! eq_impl {
1195 #[stable(feature = "rust1", since = "1.0.0")]
1200 eq_impl! { () bool char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1202 macro_rules! partial_ord_impl {
1204 #[stable(feature = "rust1", since = "1.0.0")]
1205 impl PartialOrd for $t {
1207 fn partial_cmp(&self, other: &$t) -> Option<Ordering> {
1208 match (self <= other, self >= other) {
1209 (false, false) => None,
1210 (false, true) => Some(Greater),
1211 (true, false) => Some(Less),
1212 (true, true) => Some(Equal),
1216 fn lt(&self, other: &$t) -> bool { (*self) < (*other) }
1218 fn le(&self, other: &$t) -> bool { (*self) <= (*other) }
1220 fn ge(&self, other: &$t) -> bool { (*self) >= (*other) }
1222 fn gt(&self, other: &$t) -> bool { (*self) > (*other) }
1227 #[stable(feature = "rust1", since = "1.0.0")]
1228 impl PartialOrd for () {
1230 fn partial_cmp(&self, _: &()) -> Option<Ordering> {
1235 #[stable(feature = "rust1", since = "1.0.0")]
1236 impl PartialOrd for bool {
1238 fn partial_cmp(&self, other: &bool) -> Option<Ordering> {
1239 Some(self.cmp(other))
1243 partial_ord_impl! { f32 f64 }
1245 macro_rules! ord_impl {
1247 #[stable(feature = "rust1", since = "1.0.0")]
1248 impl PartialOrd for $t {
1250 fn partial_cmp(&self, other: &$t) -> Option<Ordering> {
1251 Some(self.cmp(other))
1254 fn lt(&self, other: &$t) -> bool { (*self) < (*other) }
1256 fn le(&self, other: &$t) -> bool { (*self) <= (*other) }
1258 fn ge(&self, other: &$t) -> bool { (*self) >= (*other) }
1260 fn gt(&self, other: &$t) -> bool { (*self) > (*other) }
1263 #[stable(feature = "rust1", since = "1.0.0")]
1266 fn cmp(&self, other: &$t) -> Ordering {
1267 // The order here is important to generate more optimal assembly.
1268 // See <https://github.com/rust-lang/rust/issues/63758> for more info.
1269 if *self < *other { Less }
1270 else if *self == *other { Equal }
1277 #[stable(feature = "rust1", since = "1.0.0")]
1280 fn cmp(&self, _other: &()) -> Ordering {
1285 #[stable(feature = "rust1", since = "1.0.0")]
1288 fn cmp(&self, other: &bool) -> Ordering {
1289 // Casting to i8's and converting the difference to an Ordering generates
1290 // more optimal assembly.
1291 // See <https://github.com/rust-lang/rust/issues/66780> for more info.
1292 match (*self as i8) - (*other as i8) {
1296 // SAFETY: bool as i8 returns 0 or 1, so the difference can't be anything else
1297 _ => unsafe { unreachable_unchecked() },
1302 ord_impl! { char usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }
1304 #[unstable(feature = "never_type", issue = "35121")]
1305 impl PartialEq for ! {
1306 fn eq(&self, _: &!) -> bool {
1311 #[unstable(feature = "never_type", issue = "35121")]
1314 #[unstable(feature = "never_type", issue = "35121")]
1315 impl PartialOrd for ! {
1316 fn partial_cmp(&self, _: &!) -> Option<Ordering> {
1321 #[unstable(feature = "never_type", issue = "35121")]
1323 fn cmp(&self, _: &!) -> Ordering {
1330 #[stable(feature = "rust1", since = "1.0.0")]
1331 impl<A: ?Sized, B: ?Sized> PartialEq<&B> for &A
1336 fn eq(&self, other: &&B) -> bool {
1337 PartialEq::eq(*self, *other)
1340 fn ne(&self, other: &&B) -> bool {
1341 PartialEq::ne(*self, *other)
1344 #[stable(feature = "rust1", since = "1.0.0")]
1345 impl<A: ?Sized, B: ?Sized> PartialOrd<&B> for &A
1350 fn partial_cmp(&self, other: &&B) -> Option<Ordering> {
1351 PartialOrd::partial_cmp(*self, *other)
1354 fn lt(&self, other: &&B) -> bool {
1355 PartialOrd::lt(*self, *other)
1358 fn le(&self, other: &&B) -> bool {
1359 PartialOrd::le(*self, *other)
1362 fn gt(&self, other: &&B) -> bool {
1363 PartialOrd::gt(*self, *other)
1366 fn ge(&self, other: &&B) -> bool {
1367 PartialOrd::ge(*self, *other)
1370 #[stable(feature = "rust1", since = "1.0.0")]
1371 impl<A: ?Sized> Ord for &A
1376 fn cmp(&self, other: &Self) -> Ordering {
1377 Ord::cmp(*self, *other)
1380 #[stable(feature = "rust1", since = "1.0.0")]
1381 impl<A: ?Sized> Eq for &A where A: Eq {}
1385 #[stable(feature = "rust1", since = "1.0.0")]
1386 impl<A: ?Sized, B: ?Sized> PartialEq<&mut B> for &mut A
1391 fn eq(&self, other: &&mut B) -> bool {
1392 PartialEq::eq(*self, *other)
1395 fn ne(&self, other: &&mut B) -> bool {
1396 PartialEq::ne(*self, *other)
1399 #[stable(feature = "rust1", since = "1.0.0")]
1400 impl<A: ?Sized, B: ?Sized> PartialOrd<&mut B> for &mut A
1405 fn partial_cmp(&self, other: &&mut B) -> Option<Ordering> {
1406 PartialOrd::partial_cmp(*self, *other)
1409 fn lt(&self, other: &&mut B) -> bool {
1410 PartialOrd::lt(*self, *other)
1413 fn le(&self, other: &&mut B) -> bool {
1414 PartialOrd::le(*self, *other)
1417 fn gt(&self, other: &&mut B) -> bool {
1418 PartialOrd::gt(*self, *other)
1421 fn ge(&self, other: &&mut B) -> bool {
1422 PartialOrd::ge(*self, *other)
1425 #[stable(feature = "rust1", since = "1.0.0")]
1426 impl<A: ?Sized> Ord for &mut A
1431 fn cmp(&self, other: &Self) -> Ordering {
1432 Ord::cmp(*self, *other)
1435 #[stable(feature = "rust1", since = "1.0.0")]
1436 impl<A: ?Sized> Eq for &mut A where A: Eq {}
1438 #[stable(feature = "rust1", since = "1.0.0")]
1439 impl<A: ?Sized, B: ?Sized> PartialEq<&mut B> for &A
1444 fn eq(&self, other: &&mut B) -> bool {
1445 PartialEq::eq(*self, *other)
1448 fn ne(&self, other: &&mut B) -> bool {
1449 PartialEq::ne(*self, *other)
1453 #[stable(feature = "rust1", since = "1.0.0")]
1454 impl<A: ?Sized, B: ?Sized> PartialEq<&B> for &mut A
1459 fn eq(&self, other: &&B) -> bool {
1460 PartialEq::eq(*self, *other)
1463 fn ne(&self, other: &&B) -> bool {
1464 PartialEq::ne(*self, *other)