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.
Code
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
Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.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 Match Drives Custom Comparisons print when run?
- Running the file directly is enough — expect labeled output lines such as `tie`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.