Lifetimes Flashcards
What is lifetime in Rust?
A lifetime is a construct the compiler (or more specifically, its borrow checker) uses to ensure all borrows are valid. Specifically, a variable’s lifetime begins when it is created and ends when it is destroyed. While lifetimes and scopes are often referred to together, they are not the same.
Lifetime function constraints:
any reference must have an annotated lifetime.
any reference being returned must have the same lifetime as an input or be static.
What does ‘static’ indicates
As a reference lifetime ‘static indicates that the data pointed to by the reference lives for the remaining lifetime of the running program. It can still be coerced to a shorter lifetime
How to make variables ‘static’
There are two common ways to make a variable with ‘static lifetime, and both are stored in the read-only memory of the binary:
Make a constant with the static declaration.
Make a string literal which has type: &’static str.