struct List {
id: String,
next: Option<Box<List>>,
}
impl List {
fn remove_empty_node(&mut self) {
let mut p = self;
while let Some(n) = p.next.as_mut() {
if n.id == "" {
break;
}
p = n;
}
p.next = None;
}
}
I get the following error:
error[E0506]: cannot assign to `p.next` because it is borrowed
--> src/lib.rs:16:9
|
9 | while let Some(n) = p.next.as_mut() {
| ------ borrow of `p.next` occurs here
...
16 | p.next = None;
| ^^^^^^
| |
| assignment to borrowed `p.next` occurs here
| borrow later used here
I can't understand why the error is taking place here. Can somebody please shed some light?
I think this is a limitation of the borrow checker, though I'm not sure about the details of why it fails here...
I simplified the code to
let mut p = self;
if let Some(n) = p.next.as_mut() { // borrow of `p.next` occurs here
p = n;
}
p.next = None; // assignment to borrowed `p.next` occurs here
and it's not obvious to me what the issue with doing this is. It works if p is a reference to a List created inside the function instead of self.