I am trying to build a singly linked list:
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() {}
I am getting a compilation error:
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>>>`
While I understand the reasoning behind the error, I am not able to work around this.
I need to add an element at the last of the list. For this, I take the approach where I repeatedly loop over the next element of the list until it is not a None
and set the new value there.
I am aware that this is an imperative approach which we do in C or Java. I am not sure how to do this in Rust.