机制说明
dispatch 把三个命令映射到三个 panic 宏:greet 正常工作,fetch 用 todo! 携带冲刺备注 panic,legacy 用 unimplemented!。match 保持穷尽——占位宏占据尚未就绪的分支。
main 先静默默认 panic hook,让载荷打印归自己管,再用 catch_unwind 逐个恢复:输出打印 greet -> ok,随后是 fetch 与 legacy 载荷里的消息。unreachable! 分支记录解析器不变量,本例中从不触发。
注意事项
- todo! 与 unimplemented! 只在意图措辞上有差别。
- 静默 hook 只为输出干净,不改变载荷。
核心语句
"fetch" => todo!("fetch lands next sprint; stub keeps the match exhaustive"),
代码示例
use std::panic::{catch_unwind, set_hook};
fn dispatch(command: &str) {
match command {
"greet" => println!("greet: hello"),
"fetch" => todo!("fetch lands next sprint; stub keeps the match exhaustive"),
"legacy" => unimplemented!("legacy import is planned but not started"),
_ => unreachable!("arg parser whitelists commands before dispatch"),
}
}
fn main() {
// silence the default panic hook so payload printing stays ours
set_hook(Box::new(|_| {}));
for command in ["greet", "fetch", "legacy"] {
match catch_unwind(|| dispatch(command)) {
Ok(()) => println!("{command} -> ok"),
Err(payload) => {
let msg = payload
.downcast_ref::<String>()
.cloned()
.unwrap_or_default();
println!("{command} -> panicked: {msg}");
}
}
}
}