I have two implementation for removal function. Method 1 does not work because the compiler said curr
is borrowed.
What is the difference between while let Some(boxed_node) = curr
and match curr
?
Method 1
fn delete_method_1(&mut self, val : i32) {
let mut curr = &mut self.head;
while let Some(boxed_node) = curr {
if boxed_node.val == val {
*curr = boxed_node.next.take(); // it does not work
} else {
curr = &mut boxed_node.next
}
}
}
Error message of Method1
while let Some(boxed_node) = curr {
| ---------- `*curr` is borrowed here
26 | if boxed_node.val == val {
27 | *curr = boxed_node.next.take(); // it does not work
| ^^^^^
| |
| `*curr` is assigned to here but it was already borrowed
| borrow later used here
Method 2
fn delete_method_2(&mut self, val : i32) {
let mut curr = &mut self.head;
loop {
match curr {
None => return,
Some(boxed_node) if boxed_node.val == val => {
*curr = boxed_node.next.take();
},
Some(boxed_node) => {
curr = &mut boxed_node.next;
}
}
}
}
I expected the Method 1 works.
New contributor
Wai Ting 13 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.