I’m writing code to iteratively search a recursive data structure such as the following:
struct Tree {
payload: i32,
children: Vec<Box<Tree>>
}
Suppose that I want to walk down every left branch of the tree and modify every node encountered. For simplicity, I won't include any termination conditions. The following code is not permitted by Rust’s borrow checking rules:
fn traverse(mut n: &mut Tree) {
loop {
n.payload += 1;
n = n.children[0].as_mut();
}
}
The only way I have found of expressing this logic so far is the following:
fn traverse(n: &mut Tree) {
let mut stack: Vec<&mut Tree> = vec![n];
while let Some(x) = stack.pop() {
x.payload += 1;
stack.push(x.children[0].as_mut())
}
}
This works, but the unnecessary pushing/popping isn't very elegant.
Is there a better way of expressing this pattern in safe Rust without using recursion?