查找链表的结尾并对其进行变更

时间:2017-12-18 23:23:11

标签: rust borrow-checker

我习惯用我学到的每种新语言来实现链表,所以这只是一种教育练习。此列表仅跟踪头部。虽然很容易将其推到列表的前面,但我在实施push_back()时遇到了困难。这是代码的片段:

struct List<T> {
    head: Link<T>,
}

type Link<T> = Option<Box<Node<T>>>;

#[derive(Debug)]
struct Node<T> {
    data: T,
    next: Link<T>,
}

impl<T> List<T> {
    fn new() -> Self {
        List { head: None }
    }

    fn push_front(&mut self, data: T) {
        match self.head.take() {
            Option::None => {
                self.head = Some(Box::new(Node {
                    data: data,
                    next: None,
                }));
            }
            Option::Some(boxed_node) => {
                self.head = Some(Box::new(Node {
                    data: data,
                    next: Some(boxed_node),
                }));
            }
        };
    }

    fn push_back(&mut self, data: T) {
        let mut cur_link = &mut self.head;
        while let Some(ref mut boxed_node) = *cur_link {
            if boxed_node.next.is_none() {
                boxed_node.next = Some(Box::new(Node {
                    data: data,
                    next: None,
                }));
                break;
            }
            cur_link = &mut boxed_node.next;
        }
    }
}

On the Rust Playground

编译返回以下错误:

error[E0499]: cannot borrow `cur_link.0` as mutable more than once at a time
  --> src/main.rs:37:24
   |
37 |         while let Some(ref mut boxed_node) = *cur_link {
   |                        ^^^^^^^^^^^^^^^^^^ mutable borrow starts here in previous iteration of loop
...
47 |     }
   |     - mutable borrow ends here

error[E0506]: cannot assign to `cur_link` because it is borrowed
  --> src/main.rs:45:13
   |
37 |         while let Some(ref mut boxed_node) = *cur_link {
   |                        ------------------ borrow of `cur_link` occurs here
...
45 |             cur_link = &mut boxed_node.next;
   |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ assignment to borrowed `cur_link` occurs here

我发现借用检查器没有同情心,因为我需要在每次迭代时借用一个节点,但只在连续迭代时改变它。

0 个答案:

没有答案