实现说明
示例的行为都由函数 classify_exit、main发出。
这个示例中仅有的重复出现在 for code in [0, 2, 69, 127, 42] 里。match 逐一列出值的可能形态,漏掉的分支编译器会拒绝。
使用要点
main的演示流程是classify_exit——跑一遍文件,这条流程从头到尾可见。
常见问题
「match 分支中的范围模式」这个示例怎么运行?
文件自包含:直接运行,没有需要预先安装的依赖。
主要签名是 fn classify_exit(code: i32) -> &'static str
核心语句
let kind = match token {
'a'..='z' | 'A'..='Z' => "letter",
'0'..='9' => "digit",
_ => "other",
};
match code {
0 => "success",
1 => "generic failure",
2 => "cli usage error",
64..=78 => "sysexits convention",
126 => "cannot execute",
127 => "command not found",
_ => "unclassified",
}
代码示例
fn classify_exit(code: i32) -> &'static str {
// Range patterns fold a consecutive span into one arm; uncovered values fall to the _ wildcard
match code {
0 => "success",
1 => "generic failure",
2 => "cli usage error",
64..=78 => "sysexits convention",
126 => "cannot execute",
127 => "command not found",
_ => "unclassified",
}
}
fn main() {
for code in [0, 2, 69, 127, 42] {
println!("{code}: {}", classify_exit(code));
}
// Char ranges work the same way: inclusive ..= composes with or-patterns
let token = 'q';
let kind = match token {
'a'..='z' | 'A'..='Z' => "letter",
'0'..='9' => "digit",
_ => "other",
};
println!("{token}: {kind}");
}