Reputation: 754
Why does 'a end before 'b in this diagram? Shouldn't they both end at the same time at the end of the curly-braces?
This is Listing 10-19 from "The Rust Programming Language" book here (https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html)
Upvotes: 2
Views: 189
Reputation: 844
Here, both lifetimes 'a
and 'b
do end at the end of the curly braces. They are both created and destroyed within the same scope since neither is moved, so in this case you are correct. For our purposes, they end at the same time. However, the reason 'a
is shown to end before 'b
has to do with how the Rust borrow checker handles references, and is explained below Listing 10-18 of the same Rust Programming Language book:
// Listing 10-18
{
let r; // ---------+-- 'a
// |
{ // |
let x = 5; // -+-- 'b |
r = &x; // | |
} // -+ |
// |
println!("r: {}", r); // |
} // ---------+
The Rust borrow checker rejects the above snippet because the reference &x
outlives the value x
itself, which would cause issues. The book explains this as:
The program is rejected because 'b is shorter than 'a: the subject of the reference doesn’t live as long as the reference.
This is important. Keeping that concept in mind, let's read your snippet again:
// Listing 10-19
{
let x = 5; // ----------+-- 'b
// |
let r = &x; // --+-- 'a |
// | |
println!("r: {}", r); // | |
// --+ |
} // ----------+
The borrow checker must be able to guarantee that a reference does not outlive the value it is referencing. Therefore the lifetime of a reference must be shorter than the lifetime of the value itself. In your code snippet, the reference's lifetime 'a
is shown to end before the value's lifetime 'b
because conceptually, the reference must not exist longer than the value.
Upvotes: 1