Skip to content

Conversation

@randomPoison
Copy link
Collaborator

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.

Copy link
Collaborator

@gribozavr gribozavr left a 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.

@randomPoison
Copy link
Collaborator Author

@gribozavr I think I have addressed all of your feedback.

@gribozavr gribozavr enabled auto-merge (squash) October 31, 2025 19:21
@gribozavr gribozavr merged commit 0a017e5 into main Oct 31, 2025
40 checks passed
@gribozavr gribozavr deleted the legare/lifetimes2 branch October 31, 2025 19:37
@mgeisler
Copy link
Collaborator

mgeisler commented Nov 2, 2025

Looks really good, I wish I would have had those examples when teaching the class two weeks ago 😄

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

Successfully merging this pull request may close these issues.

4 participants