I'm having trouble understanding the difference in the two examples are and why the second doesn't work? I can't assign tho list.next in the second because it's borrowed as mutably.
struct List<T> {
value: T,
next: Option<Box<List<T>>>,
}
fn append_last<T>(mut list: &mut List<T>, append: List<T>) {
while let Some(ref mut next) = list.next {
list = next;
}
list.next = Some(Box::new(append));
}
fn append_last2<T>(mut list: &mut List<T>, append: List<T>) {
while let Some(next) = list.next.as_mut() {
list = next;
}
list.next = Some(Box::new(append));
}
fn append_last3<T>(mut list: &mut List<T>, append: List<T>) {
while let Some(next) = list.next {
list = &mut next;
}
list.next = Some(Box::new(append));
}
Why does ref mut only borrow inside the loop (when expanded match statement essentially) but the .as_mut() or &mut list.next would borrow till the end of the function essentially prohibiting me from assigning list.next at the end? Shouldn't the borrow end after the while let Some?And shouldn't the third example be the same as the first? Here it says that I can't move list.next out of the &mut list (obviously) because I' really matching on the value directly ... but isn't this exactly what I'm doing in the first example aswell? What am I missing here? error message is
error[E0506]: cannot assign to `list.next` because it is borrowed
--> src/main.rs:176:5
|
172 | fn append_last<T>(mut list: &mut List<T>, append: List<T>) {
| - let's call the lifetime of this reference `'1`
173 | while let Some(next) = list.next.as_mut() {
| ------------------
| |
| `list.next` is borrowed here
| argument requires that `list.next` is borrowed for `'1`
...
176 | list.next = Some(Box::new(append));
| ^^^^^^^^^ `list.next` is assigned to here but it was already borrowed