I was solving 203. Remove Linked List Elements and thought that I easily figured out the solution:
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct ListNode {
pub val: i32,
pub next: Option<Box<ListNode>>,
}
impl ListNode {
#[inline]
pub fn new(val: i32, next: Option<Box<ListNode>>) -> Self {
ListNode { val, next }
}
}
pub struct Solution;
impl Solution {
pub fn remove_elements(mut head: Option<Box<ListNode>>, val: i32) -> Option<Box<ListNode>> {
let mut current = &mut head;
while let Some(current_node) = current {
if current_node.val == val {
*current = current_node.next.take();
} else {
current = &mut current_node.next;
}
}
head
}
}
But unfortunately I ran into a problem:
error[E0506]: cannot assign to `*current` because it is borrowed
--> src/solutions/p0203.rs:21:17
|
19 | while let Some(current_node) = current {
| ------------ `*current` is borrowed here
20 | if current_node.val == val {
21 | *current = current_node.next.take();
| ^^^^^^^^
| |
| `*current` is assigned to here but it was already borrowed
| borrow later used here
Also after this issue I wandered how to solve it, so I look thru the solutions and found this guy, and his code has no errors.
pub fn remove_elements(mut head: Option<Box<ListNode>>, val: i32) -> Option<Box<ListNode>> {
let mut pp = &mut head;
while( (*pp).is_some() ){
if( (*pp).as_ref().unwrap().val == val ){
*pp = (*pp).as_mut().unwrap().next.take();
}else{
pp = &mut ((*pp).as_mut().unwrap().next);
}
}
head
}
I kinda feel that the problem is with Some(_) = value
, where the value is borrowed. But I like the look of while let with Some(_) in this situation, while we deal with Option, because in my opinion it feels much cleaner.
So the question is: how to fix this problem?
Eugene Michkov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.