Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
jhanschoo opened this issue Jan 5, 2023 · 0 comments
Open

Comments

@jhanschoo
Copy link

jhanschoo commented Jan 5, 2023

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

  • partially the creation of a mutable reference to an object list that externally has to last as long as list itself, thereby making impossible all future safe mutation and borrows but still allowing mutation through that mutable reference, and,
  • partially then losing access to that mutable reference (here by allowing it to fall out of scope) rather than e.g. returning it, thus making all further safe mutation impossible.

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".'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant