title: How to express iteration through mutable recursive data structure in Rust
body: <p>I’m writing code to iteratively search a recursive data structure such as the following:</p>
  
  <pre><code>struct Tree {
      payload: i32,
      children: Vec&lt;Box&lt;Tree&gt;&gt;
  }
  </code></pre>
  
  <p>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:</p>
  
  <pre><code>fn traverse(mut n: &amp;mut Tree) {
      loop {
          n.payload += 1;
          n = n.children[0].as_mut();
      }
  }
  </code></pre>
  
  <p>The only way I have found of expressing this logic so far is the following:</p>
  
  <pre><code>fn traverse(n: &amp;mut Tree) {
      let mut stack: Vec&lt;&amp;mut Tree&gt; = vec![n];
      while let Some(x) = stack.pop() {
          x.payload += 1;
          stack.push(x.children[0].as_mut())
      }
  }
  </code></pre>
  
  <p>This works, but the unnecessary pushing/popping isn't very elegant.</p>
  
  <p>Is there a better way of expressing this pattern in safe Rust without
  using recursion?</p>