Rust "Too many lists" self referencing?

Viewed 110

I'm a newcomer to Rust and while reading the chapter 6.1 of the Rust "Too many lists" series, I don't understand the passage about self referencing:

"We just committed a cardinal Rust sin: we stored a reference to ourselves inside ourselves. Somehow, we managed to convince Rust that this totally made sense in our push and pop implementations (I was legitimately shocked we did). I believe the reason is that Rust can't yet tell that the reference is into ourselves from just push and pop -- or rather, Rust doesn't really have that notion at all. Reference-into-yourself failing to work is just an emergent behaviour."

The author says sth about storing a reference to ourselves inside ourselves, but not pointing in the code where this happens. It's confusing. Can sb give a further explaination?

Here is the full code:

pub struct List<'a, T> {
    head: Link<T>,
    tail: Option<&'a mut Node<T>>, // NEW!
}

type Link<T> = Option<Box<Node<T>>>;

struct Node<T> {
    elem: T,
    next: Link<T>,
}

impl<'a, T> List<'a, T> {
    pub fn new() -> Self {
        List {
            head: None,
            tail: None,
        }
    }

    pub fn push(&'a mut self, elem: T) {
        let new_tail = Box::new(Node {
            elem: elem,
            // When you push onto the tail, your next is always None
            next: None,
        });

        // Put the box in the right place, and then grab a reference to its Node
        let new_tail = match self.tail.take() {
            Some(old_tail) => {
                // If the old tail existed, update it to point to the new tail
                old_tail.next = Some(new_tail);
                old_tail.next.as_mut().map(|node| &mut **node)
            }
            None => {
                // Otherwise, update the head to point to it
                self.head = Some(new_tail);
                self.head.as_mut().map(|node| &mut **node)
            }
        };

        // self.tail = new_tail;
    }

    pub fn pop(&'a mut self) -> Option<T> {
        // Grab the list's current head
        self.head.take().map(|head| {
            let head = *head;
            self.head = head.next;

            // If we're out of `head`, make sure to set the tail to `None`.
            if self.head.is_none() {
                self.tail = None;
            }

            head.elem
        })
    }
}
0 Answers
Related