Hi
I try to write Single Linked List to practice Rust.
But I just confused about following code.
#[derive(Debug, PartialEq, Eq)]
pub struct Node<T> {
pub val: T,
pub next: Option<Box<Node<T>>>,
}
#[derive(Debug, Default, PartialEq, Eq)]
pub struct SinglyLinkedList<T> {
pub head: Option<Box<Node<T>>>,
}
impl<T> SinglyLinkedList<T> {
pub fn new() -> Self {
SinglyLinkedList { head: None }
}
/// 1. insert in head
pub fn push_front(&mut self, val: T) {
let old_head = self.head.take();
let new_head = Some(Box::new(Node{val, next: old_head}));
self.head = new_head;
}
/// 2. insert tail - version 1
pub fn push_back(&mut self, val: T) {
let new_node = Box::new(Node { val, next: None });
let mut curr = &mut self.head;
while let Some(node) = curr {
curr = &mut node.next;
}
*curr = Some(new_node);
}
/// 3. insert tail - version 2
pub fn push_back(&mut self, val: T) {
let new_node = Box::new(Node { val, next: None });
let mut curr = &mut self.head;
while let Some(node) = curr.as_mut() {
curr = &mut node.next;
}
*curr = Some(new_node);
}
}
In 3. insert tail - version 2, the compiler would report error about
32 | *curr = Some(new_node);
| ^^^^^
| |
| `*curr` is assigned to here but it was already borrowed
| borrow later used here
"But my logic is:
curr.as_mut()creates a temporary reference that reborrows a mutable reference fromcurr, andnodethen reborrows a mutable reference from that temporary reference. After the loop,nodeshould return the loan to the temporary reference, which in turn returns the loan tocurr.Therefore,
currshould be accessible on line 32.Thanks in advance to anyone who can correct my mental model!"