-
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
Merged
Merged
Rework lifetimes section #2964
Changes from 2 commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,46 @@ | ||
| --- | ||
| minutes: 5 | ||
| --- | ||
|
|
||
| # Borrow Both | ||
|
|
||
| In this case, we have a function where either `a` or `b` may be returned. In | ||
| this case we use the lifetime annotations to tell the compiler that both borrows | ||
| may flow into the return value. | ||
|
|
||
| ```rust | ||
| fn pick<'a>(c: bool, a: &'a i32, b: &'a i32) -> &'a i32 { | ||
| if c { a } else { b } | ||
| } | ||
|
|
||
| fn main() { | ||
| let mut a = 5; | ||
| let mut b = 10; | ||
|
|
||
| let r = pick(true, &a, &b); | ||
|
|
||
| // Which one is borrowed? Should either of these | ||
| // be allowed? | ||
| // a += 7; | ||
| // b += 7; | ||
|
|
||
| dbg!(r); | ||
| } | ||
| ``` | ||
|
|
||
| <details> | ||
|
|
||
| - The `pick` function will return either `a` or `b` depending on the value of | ||
| `c`, which means we can't know at compile time which one will be returned. | ||
|
|
||
| - To express this to the compiler, we use the same lifetime for both `a` and | ||
| `b`, along with the return type. This means that the returned reference will | ||
| borrow BOTH `a` and `b`! | ||
|
|
||
| - Uncomment both of the commented lines and show that `r` is borrowing both `a` | ||
| and `b`, even though at runtime it will only point to one of them. | ||
|
|
||
| - Change the first argument to `pick` to show that the value you pass in doesn't | ||
randomPoison marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| affect borrow checking. | ||
|
|
||
| </details> | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,77 @@ | ||
| --- | ||
| minutes: 5 | ||
| --- | ||
|
|
||
| # Borrow One | ||
|
|
||
| In this example `find_nearest` takes in multiple borrows but will only return | ||
randomPoison marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| one of them. The lifetime annotations explicitly tie the returned borrow to the | ||
| corresponding argument borrow. | ||
|
|
||
| ```rust,editable | ||
| #[derive(Debug)] | ||
| struct Point(i32, i32); | ||
|
|
||
| /// Searches `points` for the point closest to `query`. | ||
| /// Assumes there's at least one point in `points`. | ||
| fn find_nearest<'a>(points: &'a [Point], query: &Point) -> &'a Point { | ||
| fn cab_distance(p1: &Point, p2: &Point) -> i32 { | ||
| (p1.0 - p2.0).abs() + (p1.1 - p2.1).abs() | ||
| } | ||
|
|
||
| let mut nearest = None; | ||
| for p in points { | ||
| if let Some((_, nearest_dist)) = nearest { | ||
| let dist = cab_distance(p, query); | ||
| if dist < nearest_dist { | ||
| nearest = Some((p, dist)); | ||
| } | ||
| } else { | ||
| nearest = Some((p, cab_distance(p, query))); | ||
| }; | ||
| } | ||
|
|
||
| nearest.map(|(p, _)| p).unwrap() | ||
| // query // What happens if we do this instead? | ||
| } | ||
|
|
||
| fn main() { | ||
| let points = &[Point(1, 0), Point(1, 0), Point(-1, 0), Point(0, -1)]; | ||
| let query = Point(0, 2); | ||
| let nearest = find_nearest(points, &query); | ||
|
|
||
| // `query` isn't borrowed at this point. | ||
| drop(query); | ||
|
|
||
| dbg!(nearest); | ||
| } | ||
| ``` | ||
|
|
||
| <details> | ||
|
|
||
| - It may be helpful to collapse the definition of `find_nearest` to put more | ||
| focus on the signature of the function. The actual logic in the function is | ||
| somewhat complex and isn't important for the purpose of borrow analysis. | ||
|
|
||
| - When we call `find_nearest` the returned reference doesn't borrow `query`, and | ||
| so we are free to drop it while `nearest` is still active. | ||
|
|
||
| - But what happens if we return the wrong borrow? Change the last line of | ||
| `find_nearest` to return `query` instead. Show the compiler error to the | ||
| students. | ||
|
|
||
| - The first thing we have to do is add a lifetime annotation to `query`. Show | ||
| students that we can add a second lifetime `'b` to `find_nearest`. | ||
|
|
||
| - Show the new error to the students. The borrow checker verifies that the logic | ||
| in the function body actually returns a reference with the correct lifetime, | ||
| enforcing that the function adheres to the contract set by the function's | ||
| signature. | ||
|
|
||
| - The "help" note in the error notes that we can add a lifetime bound `'b: 'a` | ||
| to say that `'b` will live at least as long as `'a`, which would then allow us | ||
| to return `query`. On the next slide we'll talk about lifetime variance, which | ||
| is the rule that allows us to return a longer lifetime when a shorter one is | ||
| expected. | ||
|
|
||
| </details> | ||
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,50 @@ | ||
| --- | ||
| minutes: 5 | ||
| --- | ||
|
|
||
| # Multiple Borrows | ||
|
|
||
| But what about when there are multiple borrows passed into a function and one | ||
| being returned? | ||
|
|
||
| ```rust,editable,ignore | ||
| fn multiple(a: &i32, b: &i32) -> &i32 { | ||
| todo!("Return either `a` or `b`") | ||
| } | ||
|
|
||
| fn main() { | ||
| let mut a = 5; | ||
| let mut b = 10; | ||
|
|
||
| let r = multiple(&a, &b); | ||
|
|
||
| // Which one is borrowed? Should either of these | ||
| // be allowed? | ||
randomPoison marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| a += 7; | ||
| b += 7; | ||
|
|
||
| dbg!(r); | ||
| } | ||
| ``` | ||
|
|
||
| <details> | ||
|
|
||
| - This code does not compile right now because it is missing lifetime | ||
| annotations. Before we get it to compile, use this opportunity to have | ||
| students to think about which of our argument borrows should be extended by | ||
| the return value. | ||
|
|
||
| - We pass two borrows into `multiple` and one is going to come back out, which | ||
| means we will need to extend the borrow of one of the argument lifetimes. | ||
| Which one should be extended? Do we need to see the body of `multiple` to | ||
| figure this out? | ||
|
|
||
| - When borrow checking, the compiler doesn't look at the body of `multiple` to | ||
| reason about the borrows flowing out, instead it looks only at the signature | ||
| of the function for borrow analysis. | ||
|
|
||
| - In this case there is not enough information to determine if `a` or `b` will | ||
| be borrowed by the returned reference. Show students the compiler errors and | ||
| introduce the lifetime syntax. | ||
randomPoison marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| </details> | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| --- | ||
| minutes: 5 | ||
| --- | ||
|
|
||
| # Returning Borrows | ||
|
|
||
| But we can also have our function return a reference! This means that a borrow | ||
| flows back out of a function: | ||
|
|
||
| ```rust,editable | ||
| fn identity(x: &i32) -> &i32 { | ||
| x | ||
| } | ||
|
|
||
| fn main() { | ||
| let mut x = 123; | ||
|
|
||
| let out = identity(&x); | ||
|
|
||
| // x = 5; // `x` is still borrowed! | ||
randomPoison marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| dbg!(out); | ||
| } | ||
| ``` | ||
|
|
||
| <details> | ||
|
|
||
| - Rust functions can return references, meaning that a borrow can flow back out | ||
| of a function. | ||
|
|
||
| - If a function returns a reference (or another kind of borrow), it was likely | ||
| derived from one of its arguments. This means that the return value of the | ||
| function will extend the borrow for one or more argument borrows. | ||
|
|
||
| - This case is still fairly simple, in that only one borrow is passed into the | ||
| function, so the returned borrow has to be the same one. | ||
|
|
||
| </details> | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.