实现说明
字符串字面量模式分发命令以函数 dispatch、main为骨架。
重复被限制在 for (command, amount) in [("add", 5u32), ("remove", 2), ("clear", 0), ("flush", 9)] 里——其余代码按顺序各跑一遍。通过 match 做模式匹配,值的每种形态都必须被处理。
使用要点
- 执行文件,
main会按顺序走完dispatch。
常见问题
「字符串字面量模式分发命令」这个示例怎么运行?
运行这个文件就行;脚本没有任何外部要求。
签名一览:fn dispatch(command: &str, amount: u32) -> String
核心语句
fn dispatch(command: &str, amount: u32) -> String {
// 字面量模式分发命令;&str 无法证明穷尽,必须提供兜底分支
match command {
"add" => format!("queue += {amount}"),
"remove" => format!("queue -= {amount}"),
"clear" => String::from("queue = 0"),
other => format!("unknown command {other:?}"),
}
}
let label = match code {
200..=299 => "success",
404 => "missing",
_ => "other",
};
代码示例
fn dispatch(command: &str, amount: u32) -> String {
// 字面量模式分发命令;&str 无法证明穷尽,必须提供兜底分支
match command {
"add" => format!("queue += {amount}"),
"remove" => format!("queue -= {amount}"),
"clear" => String::from("queue = 0"),
other => format!("unknown command {other:?}"),
}
}
fn main() {
for (command, amount) in [("add", 5u32), ("remove", 2), ("clear", 0), ("flush", 9)] {
println!("{command} -> {}", dispatch(command, amount));
}
// 字面量可以和范围模式混排在同一个 match 里
for code in [200u16, 404, 503] {
let label = match code {
200..=299 => "success",
404 => "missing",
_ => "other",
};
println!("{code}: {label}");
}
}