实现说明
真正干活的是函数 walk、main,其余都是接线。
这个示例中仅有的重复出现在 for child in &node.children 里。通过 match 做模式匹配,值的每种形态都必须被处理。
使用要点
- 跑完文件,输出里会留下标记——
nodes seen:、stopped:、all keys valid。 - 运行整个文件:
main会依次驱动walk。
常见问题
运行「ControlFlow 提前终止遍历」会打印什么?
文件本身就是完整程序,直接运行——输出行带有 nodes seen:、stopped:、all keys valid 这类标签。
主要签名是 fn walk(node: &Node, visit: &mut Visit) -> ControlFlow<&'static str>
核心语句
type Visit = dyn FnMut(&Node) -> ControlFlow<&'static str>;
return ControlFlow::Break(reason);
match outcome {
ControlFlow::Break(reason) => println!("stopped: {reason}"),
ControlFlow::Continue(()) => println!("all keys valid"),
}
代码示例
use std::ops::ControlFlow;
struct Node {
key: String,
children: Vec<Node>,
}
// 访问器返回 ControlFlow:Break 携带原因,walk 沿调用链短路向上
type Visit = dyn FnMut(&Node) -> ControlFlow<&'static str>;
fn walk(node: &Node, visit: &mut Visit) -> ControlFlow<&'static str> {
if let ControlFlow::Break(reason) = visit(node) {
return ControlFlow::Break(reason);
}
for child in &node.children {
if let ControlFlow::Break(reason) = walk(child, visit) {
return ControlFlow::Break(reason);
}
}
ControlFlow::Continue(())
}
fn main() {
let tree = Node {
key: String::from("app"),
children: vec![
Node { key: String::from("app.name"), children: vec![] },
Node { key: String::from("bad-prefix"), children: vec![] },
Node { key: String::from("app.tags"), children: vec![] },
],
};
let mut seen = 0usize;
let mut checker = |node: &Node| {
seen += 1;
if !node.key.starts_with("app.") {
ControlFlow::Break("key without app. prefix")
} else {
ControlFlow::Continue(())
}
};
let outcome = walk(&tree, &mut checker);
println!("nodes seen: {seen}");
match outcome {
ControlFlow::Break(reason) => println!("stopped: {reason}"),
ControlFlow::Continue(()) => println!("all keys valid"),
}
}