0
0
Rustprogramming~5 mins

Variable lifetime basics in Rust - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a variable lifetime in Rust?
A variable lifetime is the period during which a variable is valid and can be used in the program. It starts when the variable is created and ends when it goes out of scope.
Click to reveal answer
beginner
Why does Rust use lifetimes?
Rust uses lifetimes to ensure references are always valid and to prevent bugs like dangling pointers by checking how long references live at compile time.
Click to reveal answer
beginner
What happens if a reference outlives the data it points to?
Rust will give a compile-time error because the reference would be invalid, preventing unsafe memory access.
Click to reveal answer
intermediate
How do you specify a lifetime in a function signature?
You use an apostrophe followed by a name, like &'a, to tell Rust that the reference has a certain lifetime named 'a.
Click to reveal answer
beginner
What is the scope of a variable in Rust?
The scope is the part of the code where the variable is accessible. When the scope ends, the variable is dropped and its lifetime ends.
Click to reveal answer
What does a variable lifetime represent in Rust?
AThe time a variable is valid and accessible
BThe size of the variable in memory
CThe number of times a variable is used
DThe type of the variable
Why does Rust enforce lifetimes on references?
ATo allow variables to change type
BTo make the code run faster
CTo prevent invalid references and memory bugs
DTo increase the size of the program
What symbol is used to name a lifetime in Rust?
A#
B&
C$
D'
What happens if a reference's lifetime is longer than the data it points to?
ARust allows it without warnings
BRust gives a compile-time error
CThe program crashes at runtime
DThe reference is automatically copied
When does a variable's lifetime end in Rust?
AWhen the variable goes out of scope
BWhen the variable is reassigned
CWhen the program finishes
DWhen the variable is printed
Explain what a variable lifetime is and why it matters in Rust.
Think about how long a variable can be used safely.
You got /3 concepts.
    Describe how Rust uses lifetimes to prevent bugs with references.
    Focus on how Rust checks references before running the program.
    You got /3 concepts.