Ordering Match Drives Custom Comparisons

Implement custom sort rules by matching the three Ordering variants that cmp returns, breaking ties on a second field before handing the comparator to sort_by.

RustData Integrity

Code

rustsnippet
33 lines
use std::cmp::Ordering;

#[derive(Debug)]
struct Build {
    id: u32,
    duration_secs: u32,
}

// 排序规则:先比时长,相同再比 id
fn compare(a: &Build, b: &Build) -> Ordering {
    match a.duration_secs.cmp(&b.duration_secs) {
        Ordering::Equal => a.id.cmp(&b.id),
        other => other,
    }
}

fn main() {
    let mut builds = vec![
        Build { id: 42, duration_secs: 90 },
        Build { id: 7, duration_secs: 60 },
        Build { id: 13, duration_secs: 90 },
    ];
    builds.sort_by(compare);
    println!("{builds:?}");

    // cmp 返回的三值枚举本身就是模式匹配的对象
    let (left, right) = ("beta", "alpha");
    match left.cmp(right) {
        Ordering::Less => println!("{left} sorts before {right}"),
        Ordering::Equal => println!("tie"),
        Ordering::Greater => println!("{left} sorts after {right}"),
    }
}

What the code does

Ordering Match Drives Custom Comparisons keeps everything in the functions compare and main.

Branching goes through match, whose exhaustiveness checking turns forgotten cases into compile errors.

Applying it

The primary signature is fn compare(a: &Build, b: &Build) -> Ordering

The demo output is labeled (tie), so every printed line maps back to its originating operation.

Statements that matter

fn compare(a: &Build, b: &Build) -> Ordering {
match a.duration_secs.cmp(&b.duration_secs) {
Ordering::Equal => a.id.cmp(&b.id),
other => other,
}
}
match left.cmp(right) {
Ordering::Less => println!("{left} sorts before {right}"),
Ordering::Equal => println!("tie"),
Ordering::Greater => println!("{left} sorts after {right}"),
}

Interactive Tools for This Topic

FAQ

What does Ordering Match Drives Custom Comparisons print when run?
Running the file directly is enough — expect labeled output lines such as `tie`.