实现说明
用 cmp 做序列字典序比较以函数 main为骨架。
match 一条一条覆盖值的形态——不会意外落到默认分支上。
使用要点
- 演示输出是带标签的(
candidate is newer、identical、candidate is older),每个操作都会留下自己的一行标注。
常见问题
运行「用 cmp 做序列字典序比较」会打印什么?
文件本身就是完整程序,直接运行——输出行带有 candidate is newer、identical、candidate is older 这类标签。
核心语句
match deployed.iter().cmp(candidate.iter()) {
std::cmp::Ordering::Less => println!("candidate is newer"),
std::cmp::Ordering::Equal => println!("identical"),
std::cmp::Ordering::Greater => println!("candidate is older"),
}
代码示例
fn main() {
// version vectors: compare element by element, the first difference decides the order (lexicographic)
let deployed: [u32; 3] = [1, 4, 2];
let candidate: [u32; 3] = [1, 5, 0];
// iterator cmp returns an Ordering; the three outcomes are distinct variants
match deployed.iter().cmp(candidate.iter()) {
std::cmp::Ordering::Less => println!("candidate is newer"),
std::cmp::Ordering::Equal => println!("identical"),
std::cmp::Ordering::Greater => println!("candidate is older"),
}
// boolean wrappers over the same comparison: is_lt / is_ge without a match
let older: [u32; 3] = [1, 2, 9];
println!("older < deployed: {}", older.iter().cmp(deployed.iter()).is_lt());
println!("deployed >= deployed: {}", deployed.iter().cmp(deployed.iter()).is_ge());
// different lengths: with a shared prefix, the shorter one is smaller
let short: [u32; 2] = [1, 4];
println!("short prefix < deployed: {}", short.iter().cmp(deployed.iter()).is_lt());
}