在循环中更新可变引用

时间:2018-01-09 05:36:35

标签: rust

这是一个不起作用的例子:

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];
    }
}

运行这个,我得到一个错误:

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

有没有办法在不重新借用x的情况下将x更新为x个子节点之一的可变引用?

0 个答案:

没有答案