struct A {
next: Option<Box<A>>,
}
impl A {
fn grow(&mut self) {
self.next = Some(Box::new(A { next: None }));
}
}
fn main() {
let mut a = A{ next: Some(Box::new(A { next: None }))};
let mut p = &mut a;
// attempt to append to the list
loop {
match &mut p.next {
Some(n) => p = n,
None => {
p.grow();
break;
}
}
}
}
上面的代码是一个更复杂的数据结构中简化逻辑,能够重现借用检查器的投诉。
error[E0499]: cannot borrow `*p` as mutable more than once at a time
--> t.rs:19:17
|
16 | match &mut p.next {
| ----------- first mutable borrow occurs here
...
19 | p.grow();
| ^
| |
| second mutable borrow occurs here
| first borrow later used here
error: aborting due to previous error
为什么在match语句中p仍然被认为是可变借用的?而且,试图将
p.update()
fn main() {
let mut a = A{ next: Some(Box::new(A { next: None }))};
let mut p = &mut a;
// attempt to append to the list
loop {
match &mut p.next {
Some(n) => p = n,
None => {
break;
}
}
}
p.grow();
}
在这种情况下我得到了相同的错误。我知道p = n
是问题的原因,因为如果没有它就可以编译通过,但为什么呢?
p == a.next.as_mut()
的情况,您能详细说明为什么要两次引用&mut a
吗?我猜这就是我想知道的:在我的示例中只有一个 p(没有next
变量),当您给 p 赋新值时,旧的借用是否已经“释放”了呢?毕竟,无论如何都不能同时有效地访问具有两个可变借用的 a。这就是为什么我对第二个借用感到困惑的原因... - Determinant