I am a newcomer to the huge world of Rust. I have been learning it for a week and got some concept going, however something is a bit wrong with my classic implementation of singly-linked list and it is connected with borrowing and my lack of understanding of lifetimes. Here is the code:
use std::fmt::Display;
#[derive(Debug)]
struct Node<T> {
payload: T,
next: Option<Box<Node<T>>>
}
impl<T> Node<T>
where T: Display + PartialEq {
fn new(payload: T, next: Option<Box<Node<T>>>) -> Option<Box<Node<T>>> {
Some(Box::new(Node {
payload,
next
}))
}
fn print_nodes(&mut self) {
let this = self;
loop {
match this.next {
Some(_) => {
print!("{} -> ", &this.payload);
}
None => {
print!("{}", &this.payload);
break;
}
}
this = &mut this.next.unwrap();
}
}
}
fn main() {
let a = Node::new(String::from("hello"), None);
let b = Node::new(String::from("hey"), a);
let mut d = b.unwrap();
d.print_nodes();
}
Here is the error I get:
error[E0597]: borrowed value does not live long enough
--> main.rs:31:43
|
31 | this = &mut this.next.unwrap();
| ------------------^ temporary value dropped here while still borrowed
| |
| temporary value created here
32 | }
33 | }
| - temporary value needs to live until here
|
= note: consider using a `let` binding to increase its lifetime
error[E0507]: cannot move out of borrowed content
--> main.rs:31:25
|
31 | this = &mut this.next.unwrap();
| ^^^^ cannot move out of borrowed content
error[E0384]: cannot assign twice to immutable variable `this`
--> main.rs:31:13
|
20 | let this = self;
| ---- first assignment to `this`
...
31 | this = &mut this.next.unwrap();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot assign twice to immutable variable
I would be grateful if somebody could explain my mistake and recommend something to fix this.