Hi! I'm starting out with Rust and am struggling to understand exactly what's going on here.
The error I'm getting is:
error[E0506]: cannot assign to `h.next` because it is borrowed
--> src/list.rs:62:5
|
57 | while let Some(k) = h.next.as_mut() {
| ------ borrow of `h.next` occurs here
...
62 | h.next = Some(node);
| ^^^^^^
| |
| assignment to borrowed `h.next` occurs here
| borrow later used here
However, if I replace the while let block with:
while let Some(_) = h.next.as_mut() {
h = h.next.as_mut().unwrap();
ind += 1;
}
I receive no errors. I don't understand how these two are different. Isn't h.next
borrowed in both cases?
Additionally, if I remove the assignment to h
inside the while loop, no errors are thrown.
Here's the complete code:
struct Node<'a, T> {
next: Option<Box<Node<'a, T>>>,
item: &'a T,
}
pub struct List<'a, T> {
head: Option<Box<Node<'a, T>>>,
}
impl<'a, T> List<'a, T> {
pub fn new() -> Self {
Self {
head: None,
}
}
pub fn insert(&mut self, item: &'a T) {
let node = Box::new(Node::new(item));
if let None = self.head {
self.head = Some(node);
return;
}
let mut h = self.head.as_mut().unwrap();
let mut ind = 1;
while let Some(k) = h.next.as_mut() {
h = k;
ind += 1;
}
h.next = Some(node);
}
}
impl<'a, T> Node<'a, T> {
fn new(item: &'a T) -> Self {
Self {
next: None,
item,
}
}
}
An explanation of what's going on here would be amazing. Please let me know if I can clarify anything further. Thanks!