Lifetimes Flashcards

1
Q

What is lifetime in Rust?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Lifetime function constraints:

A

any reference must have an annotated lifetime.
any reference being returned must have the same lifetime as an input or be static.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What does ‘static’ indicates

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How to make variables ‘static’

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly