Hey, I'm very new to rust, attempting to create some ADTs to learn the ropes. I'm kinda stuck on trying to return the popped node from a linked list. As I understand, I'm mutably borrowing current.next
in the loop so when I then attempt to take()
it, the borrow checker flips out. I tried gpt, copilot and other sources about multiple mut borrows but can't seem to figure this out. Any tips on how to fix this would be greatly appreciated. Is this even a good approach in rust?
Minimal Reproduction:
pub struct Node {
data: i32,
next: Option<Box<Node>>,
}
pub struct LinkedList {
head: Option<Box<Node>>,
}
impl LinkedList {
fn pop(&mut self) -> Option<Box<Node>> {
if self.head.is_none() {
return None;
}
if self.head.as_mut().unwrap().next.is_none() {
return self.head.take();
}
let mut current = self.head.as_mut().unwrap();
while let Some(ref mut node) = current.next {
if node.next.is_none() {
return current.next.take();
}
current = node;
}
None
}
}
fn setupList() -> LinkedList {
let node = Box::new(Node {
data: 1,
next: Some(Box::new(Node {
data: 2,
next: Some(Box::new(Node {
data: 3,
next: Some(Box::new(Node {
data: 4,
next: Some(Box::new(Node {
data: 5,
next: None,
})),
})),
})),
})),
});
let mut list = LinkedList { head: Some(node) };
list.pop();
}
alternatively, I've also tried breaking out of the loop and returning outside, but the node borrow is still in scope apparently
while let Some(ref mut node) = current.next {
if node.next.is_none() {
break;
}
current = node;
}
current.next.take()
Error:
error[E0499]: cannot borrow `current.next` as mutable more than once at a time
--> src/adt/linked_list.rs:90:9
|
83 | while let Some(ref mut node) = current.next {
| ------------ first mutable borrow occurs here
...
90 | current.next.take()
| ^^^^^^^^^^^^
| |
| second mutable borrow occurs here
| first borrow later used here
For more information about this error, try `rustc --explain E0499`.