Я новичок в огромном мире Rust. Я изучаю его уже неделю, и у меня появилась какая-то концепция, однако что-то не так с моей классической реализацией односвязного списка, и это связано с заимствованием и моим непониманием жизней. Вот код:
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();
}
Вот ошибка, которую я получаю:
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
Я был бы признателен, если бы кто-нибудь мог объяснить мою ошибку и порекомендовать что-то, чтобы это исправить.