Trait core::cmp::Ord1.0.0 [] [src]

pub trait Ord: Eq + PartialOrd<Self> {
    fn cmp(&self, other: &Self) -> Ordering;
}

Trait for types that form a total order.

An order is a total order if it is (for all a, b and c):

  • total and antisymmetric: exactly one of a < b, a == b or a > b is true; and
  • transitive, a < b and b < c implies a < c. The same must hold for both == and >.

Derivable

This trait can be used with #[derive]. When derived, it will produce a lexicographic ordering based on the top-to-bottom declaration order of the struct's members.

How can I implement Ord?

Ord requires that the type also be PartialOrd and Eq (which requires PartialEq).

Then you must define an implementation for cmp(). You may find it useful to use cmp() on your type's fields.

Implementations of PartialEq, PartialOrd, and Ord must agree with each other. It's easy to accidentally make them disagree by deriving some of the traits and manually implementing others.

Here's an example where you want to sort people by height only, disregarding id and name:

use std::cmp::Ordering;

#[derive(Eq)]
struct Person {
    id: u32,
    name: String,
    height: u32,
}

impl Ord for Person {
    fn cmp(&self, other: &Person) -> Ordering {
        self.height.cmp(&other.height)
    }
}

impl PartialOrd for Person {
    fn partial_cmp(&self, other: &Person) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl PartialEq for Person {
    fn eq(&self, other: &Person) -> bool {
        self.height == other.height
    }
}Run

Required Methods

This method returns an Ordering between self and other.

By convention, self.cmp(&other) returns the ordering matching the expression self <operator> other if true.

Examples

use std::cmp::Ordering;

assert_eq!(5.cmp(&10), Ordering::Less);
assert_eq!(10.cmp(&5), Ordering::Greater);
assert_eq!(5.cmp(&5), Ordering::Equal);Run

Implementors