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

Compare structs where some attributes are not comparable

We can compare primitive values just as numbers using the standard comparison operators. For a custom struct, we need to derive the PartialEq and PartialOrd traits to enable comparison.

We cannot compare some of the more complex types such as HashMaps or Vectors directly using these operators. For those types, we would need to implement custom comparison logic.

Also if we have a struct with fields that do not implement PartialEq or PartialOrd, we cannot derive these traits for the struct, but we can implement them manually if needed.

use std::cmp::Ordering;
use std::collections::HashMap;

#[derive(PartialEq, PartialOrd)]
struct Point {
    x: i32,
    y: i32,
}

#[derive(PartialEq)]
struct Student {
    name: String,
    grades: HashMap<String, u8>,
}

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

fn main() {
    compare_numbers();
    compare_points();
    compare_students();
}

fn compare_numbers() {
    let a = 10;
    let b = 20;

    let result = if a > b {
        1
    } else if a < b {
        -1
    } else {
        0
    };

    println!("Comparison result: {}", result);
}

fn compare_points() {
    let p1 = Point { x: 5, y: 10 };
    let p2 = Point { x: 5, y: 15 };

    let result = if p1 > p2 {
        1
    } else if p1 < p2 {
        -1
    } else {
        0
    };

    println!("Comparison result: {}", result);
}

fn compare_students() {
    let s1 = Student {
        name: String::from("Alice"),
        grades: HashMap::from([
            (String::from("Math"), 100),
            (String::from("Literature"), 80),
        ]),
    };

    let s2 = Student {
        name: String::from("Bob"),
        grades: HashMap::from([(String::from("Math"), 90), (String::from("Literature"), 91)]),
    };

    let result = if s1 > s2 {
        1
    } else if s1 < s2 {
        -1
    } else {
        0
    };

    println!("Comparison result: {}", result);
}