3 ms·
Lifetimes in Rust are about giving you the ability to say "I have a reference, and I may not know exactly how long the underlying data may live for, but I do kn
by kibwen 2y ago
Lifetimes in Rust are about giving you the ability to say "I have a reference, and I may not know exactly how long the underlying data may live for, but I do know that it will last for at least as long as this other thing". So for example:
fn get_reference_to_first_element(x: &[u8]) -> &u8 {
return &x[0]
}
There are lifetimes here that express that the reference that is returned from this function will live as long as the reference that was passed in. In cases like this where the association is obvious, the lifetimes are implied and you don't need to write them. The desugared form looks like this:
fn get_reference_to_first_element<'a>(x: &'a [u8]) -> &'a u8 {
return &x[0]
}
Lifetimes are present on structs for the same reason.
A system that is limited to annotating only function input parameters would be limited to inferring the programmer's intent everywhere, which limits its utility to simple cases (which might be fine for some languages, but I suspect will not satisfy C++).
In addition, from glancing briefly at that video, it seems as though those five keywords seem to be more concerned with ensuring use-after-initialization, whereas Rust's lifetime system is about preventing use-after-free.