Lifetimes have a fancy name, but really they aren't super special. In fact, your source code already shows the lifetimes!
fn example() {
let v1 = Vec::new();
{
let v2 = Vec::new();
} // v2 goes out of scope here
} // v1 goes out of scope here
The lifetime of an item is basically just the braces in the source code where the variable is valid. There's a little bit of extra complexity when you have two items, but it's a straightforward extension:
fn example() {
let v1 = Vec::new(); // | Lifetime of v1
let v2 = Vec::new(); // | | Lifetime of v2
}
In this example, v1
lives a bit longer than v2
, which is only really important if you tried to refer to one in the other:
fn example() {
let mut v1 = vec![]; // | Lifetime of v1
let mut v2 = vec![()]; // | | Lifetime of v2
v1.push(&v2); // | |
}
Here, v2
will be dropped before v1
(there's a LIFO ordering to the drops), and so the reference to v2
would be invalid between when v2
is dropped and v1
is dropped.
If you are more curious about how generic lifetime parameters interact, I'd recommend checking out this answer.