实现说明
全部逻辑都在函数 classify、dispatch、main中。
迭代发生在 for n in [0, 7, 42, 500] 内部——循环之外的语句只执行一遍。match 表达式是穷尽的——编译器强制没有遗漏的分支。
使用要点
- 执行文件,
main会按顺序走完classify、dispatch。
常见问题
「用 @ 绑定在 match 中捕获子模式匹配值」这个示例怎么运行?
直接执行即可——程序只依赖运行时自身。
入口签名:fn classify(n: u32) -> String
核心语句
fn dispatch(cmd: &str) -> String {
match cmd {
// @ 也适用于 or-pattern:绑定命中值,分支里直接复用
c @ ("start" | "restart") => format!("launching via {c}"),
"stop" => "stopping".to_string(),
other => format!("unknown command {other}"),
}
}
fn classify(n: u32) -> String {
match n {
0 => "zero".to_string(),
// @ 绑定(bind)整个匹配值,同时范围子模式(subpattern)继续选分支
n @ 1..=12 => format!("small: {n}"),
n @ 13..=99 => format!("medium: {n}"),
_ => format!("large: {n}"),
}
}
代码示例
fn classify(n: u32) -> String {
match n {
0 => "zero".to_string(),
// @ 绑定(bind)整个匹配值,同时范围子模式(subpattern)继续选分支
n @ 1..=12 => format!("small: {n}"),
n @ 13..=99 => format!("medium: {n}"),
_ => format!("large: {n}"),
}
}
fn dispatch(cmd: &str) -> String {
match cmd {
// @ 也适用于 or-pattern:绑定命中值,分支里直接复用
c @ ("start" | "restart") => format!("launching via {c}"),
"stop" => "stopping".to_string(),
other => format!("unknown command {other}"),
}
}
fn main() {
for n in [0, 7, 42, 500] {
println!("{n} -> {}", classify(n));
}
for cmd in ["start", "restart", "stop", "pause"] {
println!("{cmd} -> {}", dispatch(cmd));
}
}