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.
Code
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
JSON SorterSort JSON object keys by code point ascending or descending, recursively or top-level only, preserving array order.SemVer SorterParse and sort Semantic Version 2.0.0 strings with prerelease and build metadata, respecting prerelease-below-release precedence.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.