0

I have a doubt about the definition of lifetime of a reference in Rust:

the two definitions I've found in most articles are the following two:

  1. "The lifetime of a reference is the set of lines of code in which the reference is valid".
  2. "The lifetime of a reference is the set of lines of code in which the reference needs to exist"

Now, here's my confusion. Suppose having the following code:

fn main() {
    let n = 5;
    let p = &n;               //+----------+------------+
                              //           |            |
    // do stuff...            //           | 'a         |
                              //           |            |
    println!("{}", p);        //+----------+            | 
                              //                        | 'b 
    // do something else      //                        |
    // without using p        //                        |
    // anymore...             //                        |
}                             //+-----------------------+

Then:

  • according to definition (1), 'b seems to be the correct lifetime, since n, the referenced variable continues to exist until it goes out of scope, so the reference is valid until the closing };

  • according to definition (2), 'a seems to be the correct answer, since p is only used until call to println!(), so it only needs to live until there.

Then, which definition (if any of them) is the correct one?

Personally, I've thought that def. (2) could take to some problems:

In fact, if p were passed as input to a function having signature:

fn foo<'x> (p: &'x i32) -> &'x i32

then the output result, in that case would have the same lifetime as p, i.e. 'a, making the result reference unusable after p is not used anymore.

cafce25
  • 15,907
  • 4
  • 25
  • 31
  • Both, in a sense. See [What are non-lexical lifetimes?](https://stackoverflow.com/questions/50251487/what-are-non-lexical-lifetimes) – cafce25 Aug 15 '23 at 13:28
  • 1
    In your `foo` example any usage of the returned value also counts as a use of the original reference so that's a non-issue. – cafce25 Aug 15 '23 at 13:32
  • Thanks @cafce25, however I still don't understand why would the returned value count as a use of the original reference? and, furthermore, which specific concrete lifetime, in that case, would be substituted to the generic lifetime parameter when the function is called? – Antonio Caruso Aug 15 '23 at 14:23
  • It count's as such because you tell the compiler to treat it as such by specifying the same lifetime parameter on both `p` and the return type. – cafce25 Aug 15 '23 at 14:24

0 Answers0