Skip to content

Ambiguous explanation of explicit annotated lifetimes in chapter 15.4.1 #1945

@zeonzip

Description

@zeonzip

In this example function (failed_borrow) provided by Rust By Example (15.4.1):

// snip refs for example

// A function which takes no arguments, but has a lifetime parameter `'a`.
fn failed_borrow<'a>() {
    let _x = 12;

    // ERROR: `_x` does not live long enough
    let _y: &'a i32 = &_x;
    // Attempting to use the lifetime `'a` as an explicit type annotation 
    // inside the function will fail because the lifetime of `&_x` is shorter
    // than that of `_y`. A short lifetime cannot be coerced into a longer one.
}

// snip main for example

The explanation of why declaring _y as 'a is wrong and causes an error is ambiguous and has three issues I want to comment on:

  1. At this point in the tutorial, it's important to clarify that 'a is some arbitrary lifetime that might (and usually) is longer than the function scope/lifetime itself. This would clarify that any value of 'a has to abide by that arbitrary lifetime which might be longer and can therefore not use local variables as output or as a 'a reference.

  2. The explanation states that it is wrong to use 'a as a explicit type annotation for a variable inside function bounds. It's not inherently bad to use 'a for a explicit type within the function scope, but anything stored in it has to abide by that arbitrary lifetime and therefore must be some parameter of that arbitrary lifetime from the function stored in it. In this case it might be wrong but generalizing the explanation in that way could make learners get the wrong understanding of why this won't work.

  3. Learners should be able to understand that when we write let _y: &'a i32 we mean that the reference _y is storing a value which has to live as long as the arbitrary lifetime 'a, and therefore why &_x is "shorter" than _y is because &_x is a local lifetime of the scope and may not be long enough to fulfill the arbitrary lifetime. This should be explained in a manner that doesn't have uncertainty and ambiguity, and be quick to understand and not as compact as possible.

I think these could be implemented and edit the parts to fit it, or another option is just to explain explicit lifetimes in a simpler way.

This might be nitpicky or not needed but I believe it could bring a better understanding and learning experience to new rust users which wants to learn the language.

I'd be glad to open a PR on this if it is needed.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions