I was reading the lifetimes chapter of the Rust book, and I came across this example for a named/explicit lifetime:
struct Foo<\'a> {
x: &\'a i
The lifetime annotation in the following structure:
struct Foo<'a> {
x: &'a i32,
}
specifies that a Foo
instance shouldn't outlive the reference it contains (x
field).
The example you came across in the Rust book doesn't illustrate this because f
and y
variables go out of scope at the same time.
A better example would be this:
fn main() {
let f : Foo;
{
let n = 5; // variable that is invalid outside this block
let y = &n;
f = Foo { x: y };
};
println!("{}", f.x);
}
Now, f
really outlives the variable pointed to by f.x
.