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

Improve explanation of lifetimes #2584

Merged
merged 4 commits into from
Feb 5, 2025
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Improve explanation of lifetimes
This approach seems to balance formalism with understanding. That is, it
doesn't mention contravariance, but suggests that lifetime annotations
in parameters and return values mean "opposite" things. It also
leverages the understanding that types must be specified in function
signatures, and are used to check types in the function body and at call
sites.
djmitche committed Jan 23, 2025
commit 9202650d4d390dfd60323d8689a12ae3527f6a0c
17 changes: 8 additions & 9 deletions src/lifetimes/lifetime-annotations.md
Original file line number Diff line number Diff line change
@@ -12,12 +12,9 @@ also be explicit: `&'a Point`, `&'document str`. Lifetimes start with `'` and
`'a` is a typical default name. Read `&'a Point` as "a borrowed `Point` which is
valid for at least the lifetime `a`".

Lifetimes are always inferred by the compiler: you cannot assign a lifetime
yourself. Explicit lifetime annotations create constraints where there is
ambiguity; the compiler verifies that there is a valid solution.

Lifetimes become more complicated when considering passing values to and
returning values from functions.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this removed text is load-bearing in that it counteracts a common misconception that lifetimes annotations can alter the runtime behavior of programs (in terms of how long values exist and when they are destroyed). We don't need to keep this exact phrasing but in addition to describing lifetimes as constraints we should have some explicit indication that only ownership, not lifetime annotations, control when objects are destroyed and determine the concrete lifetime of a given value.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! What do you think of the update?

Copy link
Collaborator

@fw-immunant fw-immunant Jan 27, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"The borrow checker just ensures this is done safely." implies that the borrow checker is validating ownership rather than borrowing; I think it would be better to say that "The borrow checker just validates that borrows never extend beyond the concrete lifetime of the value."

I also think it may be better to say "values" rather than "objects" in the preceding sentence. While "objects" is perfectly correct, many students come from languages which make a distinction between objects and other kinds of values and may wrongly infer that the borrow checker only applies to non-primitives.

Explicit lifetime annotations, like types, are required on function signatures
(but can be elided in common cases). These provide information for inference at
callsites and within the function body.

<!-- The multi-line formatting by rustfmt in left_most is apparently
intentional: https://github.com/rust-lang/rustfmt/issues/1908 -->
@@ -56,9 +53,11 @@ Add `'a` appropriately to `left_most`:
fn left_most<'a>(p1: &'a Point, p2: &'a Point) -> &'a Point {
```

This says, "given p1 and p2 which both outlive `'a`, the return value lives for
at least `'a`.
This says there is some lifetime `'a` which both `p1` and `p2` outlive, and
which outlives the return value. The borrow checker verifies this within the
function body, and uses this information in `main` to determine a lifetime for
`p3`.

In common cases, lifetimes can be elided, as described on the next slide.
Try dropping `p2` in `main` before printing `p3`.

</details>
13 changes: 9 additions & 4 deletions src/lifetimes/lifetime-elision.md
Original file line number Diff line number Diff line change
@@ -23,7 +23,7 @@ fn cab_distance(p1: &Point, p2: &Point) -> i32 {
(p1.0 - p2.0).abs() + (p1.1 - p2.1).abs()
}
fn nearest<'a>(points: &'a [Point], query: &Point) -> Option<&'a Point> {
fn find_nearest<'a>(points: &'a [Point], query: &Point) -> Option<&'a Point> {
let mut nearest = None;
for p in points {
if let Some((_, nearest_dist)) = nearest {
@@ -40,7 +40,11 @@ fn nearest<'a>(points: &'a [Point], query: &Point) -> Option<&'a Point> {
fn main() {
let points = &[Point(1, 0), Point(1, 0), Point(-1, 0), Point(0, -1)];
println!("{:?}", nearest(points, &Point(0, 2)));
let nearest = {
let query = Point(0, 2);
find_nearest(points, &Point(0, 2))
};
println!("{:?}", nearest);
}
```

@@ -49,12 +53,13 @@ fn main() {
In this example, `cab_distance` is trivially elided.

The `nearest` function provides another example of a function with multiple
references in its arguments that requires explicit annotation.
references in its arguments that requires explicit annotation. In `main`, the
return value is allowed to outlive the query.

Try adjusting the signature to "lie" about the lifetimes returned:

```rust,ignore
fn nearest<'a, 'q>(points: &'a [Point], query: &'q Point) -> Option<&'q Point> {
fn find_nearest<'a, 'q>(points: &'a [Point], query: &'q Point) -> Option<&'q Point> {
```

This won't compile, demonstrating that the annotations are checked for validity