Rust noob here reading about explicit annotation of lifetimes. I see there's lots of questions about it here, so I hope this post isn't duplicating.
For me, this answers the question why the compiler needs such annotations but does not answer why the user needs it. The example in the answer is:
struct Foo<'a> {
x: &'a i32,
}
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);
}
And I can see y
goes out of scope before f
, but I can't think of a case where I'd want a struct with some field that could go out of scope before the parent struct? Why would anyone need that? And by extension of that question, why not just always enforce that the fields lives as long as the parent struct?
The same question applies to functions. I can't see why I would want some function that takes some borrowed variables as an argument but the variable don't live through the entire function? The only scenario I could think of is when there's some concurrency involved.