Ordering Then With Lazy Ties

Order records with Ordering::then_with so the secondary comparison only runs when the primary keys tie, keeping expensive keys out of the hot path.

RustData Integrity

Code

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

#[derive(Debug)]
struct Job {
    priority: u8,
    id: u32,
}

fn main() {
    let mut jobs = vec![
        Job { priority: 2, id: 30 },
        Job { priority: 1, id: 10 },
        Job { priority: 2, id: 20 },
    ];

    // then_with computes the tiebreak lazily, only when priorities match
    jobs.sort_by(|a, b| a.priority.cmp(&b.priority).then_with(|| a.id.cmp(&b.id)));
    println!(
        "sorted: {:?}",
        jobs.iter().map(|job| (job.priority, job.id)).collect::<Vec<_>>()
    );

    let tie = Ordering::Equal.then_with(|| Ordering::Less);
    println!("tie resolved: {tie:?}");
    println!("primary wins: {:?}", Ordering::Greater.then_with(|| Ordering::Less));
}

What the code does

The working surface is the function main — everything else is wiring.

Watch out for

  • The dependency list is empty; the language runtime covers it all.

Applying it

Signature: fn main()

Output lines are prefixed (sorted:, tie resolved:, primary wins:), making each step’s effect easy to spot.

Statements that matter

jobs.iter().map(|job| (job.priority, job.id)).collect::<Vec<_>>()
);

Interactive Tools for This Topic

FAQ

What does Ordering Then With Lazy Ties print when run?
No setup needed: run the file and look for labeled lines like `sorted:`, `tie resolved:`, `primary wins:` in the output.