From 6dbf905b6d3dd26abb189f9693d9f0cdbe423f66 Mon Sep 17 00:00:00 2001 From: Arthur Milchior Date: Thu, 5 May 2022 07:14:51 +0200 Subject: [PATCH] Expliciting lifetime in the first example The main issue with having three lets one after the other, is that it's not clear if the lifetime created due to `let x` is the one before or after this line. Assuming I understood correctly what's going on, this example will clarify that the lifetime is created after the let. I also add a note stating what the usual notation is and warning that this longer explicit lifetime name is used only once for the sake of being as clear as possible. Other solutions I considered would be to add a "print" between two lets, this will ensure that the lifetime introduction is near a single "let", hence making it clear which "let" is concerned by the lifetime. If I got it wrong and actually the scope is introduced before the let statement, I guess at least this confirms that clarification may be helpful. --- src/lifetimes.md | 28 ++++++++++++++++------------ 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/src/lifetimes.md b/src/lifetimes.md index b35a8c6..069d0cd 100644 --- a/src/lifetimes.md +++ b/src/lifetimes.md @@ -32,9 +32,10 @@ explicitly is *extremely noisy*. All Rust code relies on aggressive inference and elision of "obvious" things. One particularly interesting piece of sugar is that each `let` statement -implicitly introduces a scope. For the most part, this doesn't really matter. -However it does matter for variables that refer to each other. As a simple -example, let's completely desugar this simple piece of Rust code: +implicitly introduces a scope immediately after the stateme. For the most part, +this doesn't really matter. However it does matter for variables that refer to +each other. As a simple example, let's completely desugar this simple piece of +Rust code: ```rust let x = 0; @@ -47,21 +48,24 @@ likely desugar to the following: ```rust,ignore -// NOTE: `'a: {` and `&'b x` is not valid syntax! -'a: { +// NOTE: `'global_lifetime: {` and `&'x_lifetime x` is not valid syntax! +'global_lifetime: { let x: i32 = 0; - 'b: { - // lifetime used is 'b because that's good enough. - let y: &'b i32 = &'b x; - 'c: { - // ditto on 'c - let z: &'c &'b i32 = &'c y; + 'x_lifetime: { + // lifetime used is 'x_lifetime because that's good enough. + let y: &'x_lifetime i32 = &'x_lifetime x; + 'y_lifetime: { + // ditto on 'y_lifetime + let z: &'y_lifetime &'x_lifetime i32 = &'y_lifetime y; } } } ``` -Wow. That's... awful. Let's all take a moment to thank Rust for making this easier. +Wow. That's... awful. Let's all take a moment to thank Rust for making this +easier. To make matter worse, traditionally, lifetimes are not as descriptive +and simply called `'a`, `'b`, and so on. We will respect this tradition going +forward. Actually passing references to outer scopes will cause Rust to infer a larger lifetime: