-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Description
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 exampleThe explanation of why declaring _y as 'a is wrong and causes an error is ambiguous and has three issues I want to comment on:
-
At this point in the tutorial, it's important to clarify that
'ais some arbitrary lifetime that might (and usually) is longer than the function scope/lifetime itself. This would clarify that any value of'ahas to abide by that arbitrary lifetime which might be longer and can therefore not use local variables as output or as a'areference. -
The explanation states that it is wrong to use
'aas a explicit type annotation for a variable inside function bounds. It's not inherently bad to use'afor 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. -
Learners should be able to understand that when we write
let _y: &'a i32we mean that the reference_yis storing a value which has to live as long as the arbitrary lifetime'a, and therefore why&_xis "shorter" than_yis 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.