I am trying to write a Singly Linked List in Rust such that we can only append to it's 'end'.
eg:
if the linked list is 1->2->3->5;
we may push(7) and the result would be
1->2->3->5->7.
This is the code:
use std::cell::{Ref, RefCell};
use std::rc::Rc;
#[derive(Debug)]
struct Node {
data: isize,
next: Rc<Option<Node>>,
}
#[derive(Debug)]
struct SinglyLinkedList {
head: Rc<Option<Node>>,
len: usize,
}
impl Node {
fn from(data: isize) -> Self {
Self {
data, next:Rc::from(None)
}
}
}
impl SinglyLinkedList {
fn new() -> Self {
Self {
head: Rc::from(None),
len: 0,
}
}
fn append(&mut self, data: isize) {
self.len += 1;
let new_node = Node::from(data);
if self.len == 0 {
self.head = Rc::from(Some(new_node));
}
else {
let mut curr_node = self.head.clone(); // Getting a mut reference to a Rc<Option<Node>>
for _ in 0..self.len-1 {
// Traversing the Linked List by going to the next node until we reach the end where we append the new_node
curr_node = curr_node.unwrap().next.clone();
}
curr_node.unwrap().next = Rc::from(Some(new_node));
}
}
}
fn main() {
let mut list = SinglyLinkedList::new();
list.append(11);
println!("{:?}", list);
}
When I execute it, I get the following error:
error[E0507]: cannot move out of an `Rc`
--> src/main.rs:84:29
|
84 | curr_node = curr_node.unwrap().next.clone();
| ^^^^^^^^^^^^^^^^^^ move occurs because value has type `Option<Node>`, which does not implement the `Copy` trait
|
help: consider borrowing the `Option`'s content
|
84 | curr_node = curr_node.unwrap().as_ref().next.clone();
| +++++++++
According to my understanding, I used Rc<T> because I would have 2 owners during the append function: One the Node before the a Node (could be self.head) and the other would be curr_node which I use to traverse the Linked List. I also need mutability and tried using RefCell<T> but couldn't get it to work. I do not understand what to do to not get this error.