我正在尝试建立一个单链表:
pub struct Node<T> {
pub element: T,
pub next: Option<Box<Node<T>>>,
}
struct List<T> {
head: Option<Node<T>>,
}
impl<T> List<T> {
fn new() -> Self {
List { head: None }
}
fn add(&mut self, element: T) {
let node = Node {
next: None,
element,
};
// get the node at the end of the list
match self.head {
None => self.head = Some(node),
Some(_) => {
let mut last_node: Option<Box<&Node<T>>> =
Some(Box::new(self.head.as_ref().unwrap()));
while let Some(node) = last_node {
let n = node.next.take().map(|n| &n);
last_node = n;
}
}
}
}
}
fn main() {}
我收到编译错误:
error[E0308]: mismatched types
--> src/main.rs:28:33
|
28 | last_node = n;
| ^ expected struct `std::boxed::Box`, found reference
|
= note: expected type `std::option::Option<std::boxed::Box<&Node<T>>>`
found type `std::option::Option<&std::boxed::Box<Node<T>>>`
虽然我理解错误背后的原因,但我无法解决这个问题。
我需要在列表的最后添加一个元素。为此,我采用的方法是重复循环遍历列表的下一个元素,直到它不是None
并在那里设置新值。
我知道这是我们用C或Java做的必要方法。我不知道如何在Rust中做到这一点。