-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Rework lifetimes section #2964
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
Rework lifetimes section #2964
Conversation
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thank you, this is indeed a much better, step by step presentation!
Could you add a redirect for the deleted src/lifetimes/lifetime-elision.md to one of the new pages? The redirects are managed by comprehensive-rust.git/book.toml.
|
@gribozavr I think I have addressed all of your feedback. |
|
Looks really good, I wish I would have had those examples when teaching the class two weeks ago 😄 |
This PR attempts to rework the lifetimes section to better contextualize how lifetimes are used and to try to lead through a series of examples more naturally. I think the current version of the lifetimes section falls short in a handful of ways that make it hard to teach in class. For a long time I've been experimenting with different ways to discuss the topic, and in my recent classes I think I've finally hit on an approach that works. The changes in this PR capture the approach I've been using.
The core idea is to contextualize lifetime annotations by looking at what happens when we return a reference from a function. We start with a simple example that doesn't return a reference to show that the borrow ends when the function returns. Then we look at a function that returns a reference and show that it extends the borrow that was passed into the function. With that context, we then look at cases where we need lifetime annotations, specifically examples where there are two ref arguments and a returned ref. We look at both possible cases: A function where either of the argument refs may be returned, and a case where only one will be returned. In both cases we show how we use lifetime annotations to tell the compiler what the returned ref is borrowing.
I haven't had a chance to use these slides in class yet so I'm putting this up as a draft PR while I continue to iterate on it so that other folks can start giving feedback.