我正在编写一个fn来从LinkedList中的最后一个位置弹出元素,但是在这个场景中发生了一个双mut引用错误,我试图获取倒数第二个 node ,这样我就可以砍掉 tail
fn pop(&mut self) -> Option<T> {
match self.head {
None => None,
Some(ref mut head) => {
let mut curr = head;
while let Some(ref mut next) = curr.next {
if next.next.is_none() {
break;
}
curr = next;
}
let taken = curr.next.take();
taken.map(|x| x.data)
}
}
}
但代码会在没有判断的情况下编译
fn pop(&mut self) -> Option<T> {
match self.head {
None => None,
Some(ref mut head) => {
let mut curr = head;
while let Some(ref mut next) = curr.next {
// if next.next.is_none() {
// break;
// }
curr = next;
}
let taken = curr.next.take();
taken.map(|x| x.data)
}
}
}
误差率
error[E0499]: cannot borrow `curr.next` as mutable more than once at a time
--> src\main.rs:70:29
|
62 | while let Some(ref mut next) = curr.next {
| ------------ first mutable borrow occurs here
...
70 | let taken = curr.next.take();
| ^^^^^^^^^^^^^^^^
| |
| second mutable borrow occurs here
| first borrow later used here
因为我对Rust 还不熟悉,所以我好像搞不清楚这个问题.任何帮助都将不胜感激.
完整代码
use std::fmt::Debug;
#[derive(Debug)]
struct Node<T> {
data: T,
next: Option<Box<Node<T>>>,
}
#[derive(Debug)]
struct LinkedList<T> {
head: Option<Box<Node<T>>>,
len: usize,
}
impl<T: Debug> LinkedList<T> {
fn new() -> Self {
Self { head: None, len: 0 }
}
fn push(&mut self, data: T) {
match self.head {
None => self.head = Some(Box::new(Node::new(data))),
Some(ref mut head) => {
let mut curr = head;
while let Some(ref mut next) = curr.next {
curr = next;
}
curr.next = Some(Box::new(Node::new(data)));
}
}
self.len += 1;
}
// head -> 1 -> 2
fn pop(&mut self) -> Option<T> {
match self.head {
None => None,
Some(ref mut head) => {
let mut curr = head;
while let Some(ref mut next) = curr.next {
// if next.next.is_none() {
// break;
// }
curr = next;
}
let taken = curr.next.take();
taken.map(|x| x.data)
}
}
}
}
impl<T> Node<T> {
fn new(data: T) -> Self {
Node { data, next: None }
}
}