0 day streak
rust / expert
Snippet

Customizing Short-Circuiting Behavior via ControlFlow

The `ControlFlow` enum in standard library standardizes early-exit control flow patterns (Break vs Continue). It allows users to write custom traversal algorithms that propagate short-circuit values seamlessly using the `?` operator without resorting to misuse of the `Result` or `Option` types.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
use std::ops::ControlFlow;
struct Node {
val: i32,
children: Vec<Node>,
}
fn search_sum(node: &Node, target: i32, acc: &mut i32) -> ControlFlow<i32, ()> {
*acc += node.val;
if *acc >= target {
return ControlFlow::Break(*acc);
}
for child in &node.children {
search_sum(child, target, acc)?;
}
ControlFlow::Continue(())
}
Breakdown
1
fn search_sum(...) -> ControlFlow<i32, ()> {
Declares a function returning ControlFlow with an early-exit payload of i32 or continue signal of ().
2
return ControlFlow::Break(*acc);
Triggers short-circuiting control flow by packing the early return value into the Break variant.
3
search_sum(child, target, acc)?[...] ;
Uses the native `?` operator to automatically bubble up Break payloads up the recursion stack.