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:
- "The lifetime of a reference is the set of lines of code in which the reference is valid".
- "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, sincen
, 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, sincep
is only used until call toprintln!()
, 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.