这是一个不起作用的例子:
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
个子节点之一的可变引用?