【发布时间】:2021-12-04 01:48:26
【问题描述】:
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 case 中仍然认为 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 导致了这个问题,因为它在没有它的情况下编译通过,但是为什么呢?
【问题讨论】:
标签: rust borrow-checker