Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Manually implement ordering

  • PartialOrd

  • PartialEq

  • partial_cmp

  • eq

  • In rare case we might want to have an ordering that is not the same as the default implementation of PartialOrd. In these cases we can implement it ourselves.

  • For this we need to implement both PartialEq and PartialOrd.

  • In our case the functions only take into account the height field.

  • the #[allow(dead_code)] is only needed in this example because we never access the id and name fields.

use std::cmp::Ordering;

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

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

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

fn main() {
    let a = Person {
        id: 1,
        name: String::from("Foo"),
        height: 160,
    };

    let b = Person {
        id: 1,
        name: String::from("Foo"),
        height: 180,
    };

    let c = Person {
        id: 1,
        name: String::from("Foo"),
        height: 160,
    };

    let x = Person {
        id: 2,
        name: String::from("Bar"),
        height: 180,
    };

    println!("{}", a < b);
    println!("{}", a == c);
    println!("{}", b == x);
}
true
true
true