在一会儿let循环超出范围后,为什么编译器会警告我有关可变的借项?

时间:2019-06-19 22:59:17

标签: rust borrow-checker

full code

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,
}))

但是它仍然不起作用...

0 个答案:

没有答案