Delete a node in singly linked list in Rust
There isn't really code that can go in that space to fix it; you'll need to make some bigger changes.
One of the problems is that you have mutably borrowed the current node in current_node
, but then need to mutate it while that reference still exists.
Making use of non-lexical lifetimes in Edition 2018, you can do:
impl LinkedList {
fn remove(&mut self, v: usize) -> Option<usize> {
let mut current = &mut self.head;
loop {
match current {
None => return None,
Some(node) if node.v == v => {
*current = node.next.take();
return Some(v);
},
Some(node) => {
current = &mut node.next;
}
}
}
}
}
Somehow, using the match guard if node.v == v
to make two match arms, instead of using an if
condition inside one match arm, lets the borrower checker deduce that this is safe. I'm not sure why the if
statement inside the match arm isn't allowed - there are some of the opinion that this could be a bug.