Linked list loop until last node

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 :slight_smile:

    fn mut_tail2(&mut self) -> &mut Self {
        let mut current = self;
        loop {
            if current.next.is_none() {
                return current;
            } else {
                current = current.next.as_mut().unwrap();
            }
        }
    }
1 Like

If you want to implement linked lists in rust, this book is mandatory reading: Introduction - Learning Rust With Entirely Too Many Linked Lists

3 Likes