(Every statement marked with ? wishes to be asserted)
I'm just coming along with lifetimes slowly.
As lifetime elision helps to omit explicitly describing a lifetime(?) there are cases where we need to describe them.
An example might be a struct which holds a reference:
struct Person<a'>{
car: &'a Car
}
Am I right with the following assumption that,
a struct is a value type - therefore its memory lies on the stack. After the scope ends where this struct is used in - the struct will die. But since this struct holds a reference to a Car and this reference might be borrowed to somewhere else - the struct NEEDS to stay alive as long as the Car reference is in use. The Lifetime 'a therefore tells the Person struct to stay alive as long as Car is in use.(?)
to be honest I don't believe myself with this statement above. Because in other definitions of the rust lifetime I understood it so - that the Car needs to stay alive at least as long as 'a so Person won't have a dangling pointer.
As lifetime elision helps to omit explicitly describing a lifetime (?) there are cases where we need to describe them.
No As here, lifetime elision is simply about making your life easier (both as writer and reader). The lifetimes are still present (semantically) but need not be explicitly denoted (syntactically).
Lifetime elision does not work in struct
definition, as far as I know. It works in functions signatures and bodies.
But since this struct holds a reference to a Car and this reference might be borrowed to somewhere else - the struct NEEDS to stay alive as long as the Car reference is in use.
No. The goal of lifetime is to avoid dangling references, and indicate borrowing relationships.
- Dangling references are references that refer to (long-)dead values, possibly in freed memory or (worse) in reused memory.
- Borrowing relationships are used by the borrow checker to track whether someone still has a reference into a value or not; while someone has a reference into a value, it should not be moved or changed to another type lest said reference becomes dangling.
For a deeper explanation of dangling references, I recommend this question.
Therefore, lifetimes are about ensuring that a reference NEVER outlives the value it refers to.
The constraint, therefore, is the opposite of your belief: the goal of 'a
here is to let the compiler ensure that your Person
never outlives the Car
it refers to.
It's the other way around: The struct contains a reference, thus it may not outlive the thing the reference points to.