Hi, I wrote a simple linked list, which has a pop function (pop last Node, and return it's value). I search for the last Node that has a next field of value None, and assign last Node=None.
But the compiler complain that after I break out of loop, borrow still exist, so that I cannot assign value. Any suggestion? Thanks!
pub struct SimpleLinkedList<T> {
head: Option<Box<Node<T>>>,
}
struct Node<T> {
data: T,
next: Option<Box<Node<T>>>,
}
impl<T: PartialEq + Copy> SimpleLinkedList<T> {
pub fn pop(&mut self) -> Option<T> {
let mut ptr = &mut self.head;
let mut ret = None;
loop {
match ptr {
//Borrow happened
Some(ref mut node) => {
if node.next == None {
ret = Some(node.data);
break;
} else {
ptr = &mut node.next;
}
}
None => {
return None;
}
}
}
// Out of loop scope, but still borrowed?
*ptr = None;
ret
}
}
error[E0506]: cannot assign to `*ptr` because it is borrowed
--> src\lib.rs:74:9
|
61 | Some(ref mut node) => {
| ------------ borrow of `*ptr` occurs here
...
74 | *ptr = None;
| ^^^^
| |
| assignment to borrowed `*ptr` occurs here
| borrow later used here