hey,
I am trying to tweak an implementation of a liked list from the book "code like a pro in rust" chapter 5:
struct ListItem<T> {
data: Box<T>,
next: Option<Box<ListItem<T>>>,
}
struct SinglyLinkedList<T> {
head: ListItem<T>,
}
impl<T> ListItem<T> {
fn new(data: T) -> Self {
ListItem {
data: Box::new(data),
next: None,
}
}
fn next(&self) -> Option<&Self> {
if let Some(next) = &self.next {
Some(&*next)
} else {
None
}
}
fn mut_tail(&mut self) -> &mut Self {
if self.next.is_some() {
self.next.as_mut().unwrap().mut_tail()
} else {
self
}
}
fn data(&self) -> &T {
self.data.as_ref()
}
}
impl<T> SinglyLinkedList<T> {
fn new(data: T) -> Self {
SinglyLinkedList {
head: ListItem::new(data),
}
}
fn append(&mut self, data: T) {
let mut tail = self.head.mut_tail();
tail.next = Some(Box::new(ListItem::new(data)));
}
fn head(&self) -> &ListItem<T> {
&self.head
}
}
trying to re-implement fn mut_tail
so that it uses a loop instead of recursion:
fn mut_tail2(&mut self) -> &mut Self {
let current = self;
loop {
if current.next.is_none() {
return current; // cannot return value referencing temporary value + cannot move out of `current.next` which is behind a mutable reference
} else {
current = current.next.unwrap().as_mut(); //cannot assign twice to immutable variable
}
}
}
but I get several compiler errors here that I can't solve:
any help would be appreciated