pub struct List<T> {
pub head: Option<Node<T>>,
len: usize,
}
impl<T> List<T> {
pub fn new() -> Self {
List { head: None, len: 0 }
}
pub fn push_end(&mut self, data: T) {
if self.len == 0 {
self.head = Some(Node { data, next: None })
} else {
let mut temp: &mut Node<T> = self.head.as_mut().unwrap();
// while let Some(n) = &mut temp.next {
// temp = &mut *n;
// }
while temp.next.is_some() {
temp = temp.next.as_mut().unwrap();
}
temp.next = Some(Box::new(Node { data, next: None }))
}
self.len += 1;
}
}
pub struct Node<T> {
pub data: T,
pub next: Option<Box<Node<T>>>,
}
fn main() {
let mut l = List::new();
l.push_end("hello");
l.push_end("world");
println!(
"{} {}",
l.head.as_ref().unwrap().data,
l.head.as_ref().unwrap().next.as_ref().unwrap().data
)
}
当我切换两个循环时:
while let Some(n) = &mut temp.next {
temp = &mut *n;
}
// while temp.next.is_some() {
// temp = temp.next.as_mut().unwrap();
// }
我无法分配给temp.next
,因为:
error[E0506]: cannot assign to `temp.next` because it is borrowed
--> src/main.rs:24:13
|
17 | while let Some(n) = &mut temp.next {
| -------------- borrow of `temp.next` occurs here
...
24 | temp.next = Some(Box::new(Node { data, next: None }))
| ^^^^^^^^^
| |
| assignment to borrowed `temp.next` occurs here
| borrow later used here
n
应该在while循环结束时超出范围。
我尝试显式添加范围:
let mut temp: &mut Node<T> = self.head.as_mut().unwrap();
{
while let Some(n) = &mut temp.next {
temp = &mut *n;
}
}
temp.next = Some(Box::new(Node{
data,
next: None,
}))
但是它仍然不起作用...