I wanted to implement a linked list from scratch. The basic idea is that new elements are added to the end of the list, requiring the program to cycle to the end to reach the last element to append.
I realise that there is a LinkedList
type as part of the standard library but I am trying to implement this for educational purposes.
I also took a look at the Rust tutorial Learn Rust With Entirely Too Many Linked Lists but this didn't really have what I was looking for as it implemented stacks, placing new elements at the start.
The code I have come up with is as follows:
#[derive(Debug)]
struct Node {
value: i32,
next: Option<Box<Node>>,
}
struct LinkList {
head: Option<Box<Node>>,
}
impl LinkList {
fn has_head(&self) -> bool {
self.head.is_none()
}
fn insert_node(&mut self, node: Node) {
if self.has_head() {
self.head = Some(Box::new(node));
} else {
let mut curr = &mut self.head;
let mut cont = true;
while cont {
match curr {
Some(ref mut p) => {
println!("has value {:?}", p);
if p.next.is_none() {
cont = false;
}
else {
curr = &mut p.next;
}
},
None => cont = false,
}
}
match curr {
Some(ref mut p) => {
println!("Yay");
p.next = Some(Box::new(node));
},
None => println!("Something has gone wrong..."),
}
}
}
}
With the main function being:
fn main() {
let n1 = Node {
value: 1,
next: None
};
let n2 = Node {
value: 2,
next: None
};
let n3 = Node {
value: 3,
next: None
};
let mut l = LinkList { head: None };
l.insert_node(n1);
l.insert_node(n2);
l.insert_node(n3);
println!("{:?}", l.head);
}
I think I am pretty close but the error I am currently getting is
error[E0503]: cannot use `*curr` because it was mutably borrowed
--> src/lib.rs:25:21
|
25 | Some(ref mut p) => {
| ^^^^^---------^
| | |
| | borrow of `curr.0` occurs here
| use of borrowed `curr.0`
| borrow later used here
error[E0499]: cannot borrow `curr.0` as mutable more than once at a time
--> src/lib.rs:25:26
|
25 | Some(ref mut p) => {
| ^^^^^^^^^ mutable borrow starts here in previous iteration of loop
error[E0503]: cannot use `*curr` because it was mutably borrowed
--> src/lib.rs:39:17
|
25 | Some(ref mut p) => {
| --------- borrow of `curr.0` occurs here
...
39 | Some(ref mut p) => {
| ^^^^^^^^^^^^^^^
| |
| use of borrowed `curr.0`
| borrow later used here
error[E0499]: cannot borrow `curr.0` as mutable more than once at a time
--> src/lib.rs:39:22
|
25 | Some(ref mut p) => {
| --------- first mutable borrow occurs here
...
39 | Some(ref mut p) => {
| ^^^^^^^^^
| |
| second mutable borrow occurs here
| first borrow later used here
I understand the basics of Rust's ownership rules and can kinda understand why this issue is occurring. How do I work with the ownership rules to achieve what I need?