rust-unofficial / too-many-lists

Learn Rust by writing Entirely Too Many linked lists
https://rust-unofficial.github.io/too-many-lists/
MIT License
3.16k stars 276 forks source link

Clarify "we stored a reference to ourselves inside ourselves" in 6.1 #263

Open jhanschoo opened 1 year ago

jhanschoo commented 1 year ago

See related issue #203

We just committed a cardinal Rust sin: we stored a reference to ourselves inside ourselves.

The informal phrasing/understanding here is very confusing to me, and has wasted a couple hours of my time. Let me use the no-op in the linked issue as an example.

impl<'a, T: Default> List<'a, T> {
    pub fn push(&'a mut self, elem: T) {
    }

    pub fn pop(&'a mut self) -> Option<T> {
        Some(Default::default())
    }
}

...

// in tests
assert_eq!(list.pop(), None);
list.push(1);

Here is how I understand it and how I would explain it. When list.pop(...) is called, a mutable reference to list is created that is expected to have lifetime 'a. Even though self later falls out of scope in the implementation, from the calling code's perspective, this does not matter. When we later call list.push(..), we again try to create a mutable reference to list... within the expected lifetime of the first mutable reference to list... since list is still alive.

There has not been any "reference to ourselves inside ourselves" in, say, a C++ sense. We have previously created such mutable references in the course of this tutorial, but their implicit input lifetimes were limited to the body of the method. The sin that has happened was

Similarly, the later elaboration is confusing:

But as soon as we try to actually use the list, the compiler quickly goes "yep you've borrowed self mutably for 'a, so you can't use self anymore until the end of 'a" but also "because you contain 'a, it must be valid for the entire list's existence".

I would rephrase it as:

'yep you've borrowed self mutably for 'a, so you can't mutate or borrow self anymore until the end of 'a" but also "because list has lifetime 'a, said end of 'a is the end of list's existence".'