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

#[lang = "ord"]
pub trait Ord: Eq + PartialOrd<Self> { fn cmp(&self, other: &Self) -> Ordering; fn max(self, other: Self) -> Self { ... }
fn min(self, other: Self) -> Self { ... } }

Trait for types that form a total order.

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

Derivable

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

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

Provided Methods

Compares and returns the maximum of two values.

Returns the second argument if the comparison determines them to be equal.

Examples

assert_eq!(2, 1.max(2));
assert_eq!(2, 2.max(2));Run

Compares and returns the minimum of two values.

Returns the first argument if the comparison determines them to be equal.

Examples

assert_eq!(1, 1.min(2));
assert_eq!(2, 2.min(2));Run

Implementations on Foreign Types

impl Ord for CpuidResult
[src]

impl<T> Ord for NonZero<T> where
    T: Zeroable + Ord
[src]

Implementors