2

This is an example that doesn't work:

fn main() {
    struct Node {
        children: Vec<Node>,
    }
    impl Node {
        fn new() -> Node {
            Node {
                children: Vec::new(),
            }
        }
    }

    let mut node = Node::new();
    node.children.push(Node::new());

    let mut x = &mut node;
    loop {
        x = &mut x.children[0];
    }
}

Running this, I get an error of:

error[E0506]: cannot assign to `x` because it is borrowed
  --> src/main.rs:18:9
   |
18 |         x = &mut x.children[0];
   |         ^^^^^^^^^----------^^^
   |         |        |
   |         |        borrow of `x` occurs here
   |         assignment to borrowed `x` occurs here

error[E0499]: cannot borrow `x.children` as mutable more than once at a time
  --> src/main.rs:18:18
   |
18 |         x = &mut x.children[0];
   |                  ^^^^^^^^^^ mutable borrow starts here in previous iteration of loop
19 |     }
20 | }
   | - mutable borrow ends here

Is there any way to update x to a mutable reference of one of x's child nodes without re-borrowing x?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Bokwan D.
  • 29
  • 2
  • Relevant: [Obtaining a mutable reference by iterating a recursive structure](https://stackoverflow.com/a/37987197/2731452) – red75prime Jan 09 '18 at 05:40
  • 2
    See also [this example](https://github.com/nikomatsakis/nll-rfc/blob/master/0000-nonlexical-lifetimes.md#problem-case-4-mutating-mut-references) in the RFC for non-lexical lifetimes. Your code just works with NLLs enabled ([playgorund](https://play.rust-lang.org/?gist=758460768747fffc359ece9747c6ab4e&version=nightly)). – Sven Marnach Jan 09 '18 at 13:27
  • 1
    @SvenMarnach wow thanks! This is *exactly* what I was looking for!! – Bokwan D. Jan 10 '18 at 01:26

0 Answers0