Early Exit Traversal With ControlFlow

Propagate a stop signal through recursive visitors with std::ops::ControlFlow, so the first failing node halts the whole walk without Result plumbing.

RustConfig Management

Code

rustsnippet
49 lines
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"),
    }
}

How the stop signal travels

walk(node, visit) runs the visitor once on the node, then once per child through for child in &node.children. Every ControlFlow::Break(reason) is returned up the call chain immediately — the two if let guards make each level short-circuit instead of continuing the sibling loop — so the first failing node halts the entire traversal without any Result plumbing. The visitor itself is type Visit = dyn FnMut(&Node) -> ControlFlow<&'static str>, consumed as &mut Visit so the closure can keep mutable state across calls.

What this particular demo prints

The checker closure breaks on any key that fails node.key.starts_with("app.") — and the root’s key is "app", which does not carry the dot. The walk therefore stops at the very first visited node:

nodes seen: 1
stopped: key without app. prefix

seen was incremented once before the break, and the three children (app.name, bad-prefix, app.tags) are never visited. The match on outcome prints the stopped: line from the carried &'static str; the all keys valid arm belongs to the ControlFlow::Continue(()) case, which this data does not take.

The line that halts a level

if let ControlFlow::Break(reason) = walk(child, visit) {
    return ControlFlow::Break(reason);
}

walk is a private free function — no pub — so the propagation pattern, not an exported API, is what this file offers: the same two if let guards are all a caller needs to copy into their own traversal.

Interactive Tools for This Topic

FAQ

What does Early Exit Traversal With ControlFlow print when run?
Run it as a complete program — the output lines carry labels such as `nodes seen:`, `stopped:`, `all keys valid`.