0
0
Rustprogramming~5 mins

Lifetime annotations in Rust - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a lifetime annotation in Rust?
A lifetime annotation tells Rust how long a reference should be valid. It helps the compiler check that references do not outlive the data they point to.
Click to reveal answer
beginner
Why do we need lifetime annotations in Rust?
We need lifetime annotations to avoid dangling references and ensure memory safety by making sure references do not live longer than the data they refer to.
Click to reveal answer
intermediate
Explain the syntax of a lifetime annotation with an example.
A lifetime annotation uses an apostrophe followed by a name, like 'a. For example, fn example<'a>(x: &'a str) -> &'a str means the returned reference lives at least as long as x.
Click to reveal answer
intermediate
What does the following function signature mean?<br>
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str
It means both input string references x and y must live at least as long as lifetime 'a, and the returned reference will also live at least as long as 'a. This ensures the returned reference is valid as long as both inputs.
Click to reveal answer
intermediate
Can Rust always infer lifetimes without annotations?
Rust can infer lifetimes in simple cases using lifetime elision rules. But for complex cases, explicit lifetime annotations are needed to clarify how references relate.
Click to reveal answer
What does a lifetime annotation in Rust specify?
AHow long a reference is valid
BThe size of a variable
CThe type of a variable
DThe value of a variable
Which symbol starts a lifetime annotation in Rust?
A$
B&
C#
D'
In the function signature fn foo<'a>(x: &'a i32) -> &'a i32, what does 'a represent?
AA type parameter
BA lifetime parameter
CA variable name
DA constant value
Why might Rust require explicit lifetime annotations?
ATo clarify complex reference relationships
BTo improve performance
CTo reduce code size
DTo allow unsafe code
What happens if a reference outlives the data it points to in Rust?
AThe reference becomes null
BThe program crashes immediately
CRust compiler gives an error
DRust ignores it
Explain in your own words what lifetime annotations are and why they are important in Rust.
Think about how Rust keeps track of how long references are valid.
You got /3 concepts.
    Describe the syntax of lifetime annotations and give a simple example function signature using them.
    Look at how <code>&#39;a</code> is used in function parameters and return types.
    You got /3 concepts.