I hope it’s okey to ask for help on exercises here as well; I am currently working on the LinkedList, and I cannot seem to get a hold of it. Here’s what I’ve got so far:
use std::iter::FromIterator; [5/1974]
pub struct SimpleLinkedList<T> {
head: Option<Box<Node<T>>>,
len: usize,
}
struct Node<T> {
data: T,
next: Option<Box<Node<T>>>,
}
impl<T> Node<T> {
pub fn new(_element: T, next: &Option<Box<Node<T>>>) -> Self {
Node {
data: _element,
next: None,
}
}
}
impl<T> SimpleLinkedList<T> {
pub fn new() -> Self
{
SimpleLinkedList {
head: None,
len: 0,
}
}
pub fn is_empty(&self) -> bool {
match self.head {
None => true,
_ => false,
}
}
pub fn len(&self) -> usize {
self.len
}
pub fn push(&mut self, _element: T) {
self.len += 1;
self.head = Some(Box::new(Node::new(_element, &self.head)));
}
pub fn pop(&mut self) -> Option<T> {
if self.is_empty() {
return None
}
self.len -= 1;
let old_node = self.head.as_ref().unwrap();
Some(old_node.data)
}
// -- snip --
I am currently working on the pop
-Function and I cannot seem to get it to work; the thing that I am wanting to do is, to access the data part of the head node and wrap it into an Option<T>
, but no matter what I try, it just won’t let me access that data.
Latest error message says:
cannot move out of
old_node.data
which is behind a shared reference: move occurs becauseold_node.data
has typeT
, which does not implement theCopy
trait
I was also trying working with *
, and working with &mut
, etc. but I am not getting any closer.
What am I doing wrong here? It cannot be that hard to access that data? I also looked into Copy trait, but somehow I feel that this is growing out of hand and out of scope of the exercise?