0
0
Rustprogramming~5 mins

Lifetime elision rules in Rust - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of lifetime elision in Rust?
Lifetime elision allows Rust to infer lifetimes in function signatures without explicit annotations, making code easier to read and write.
Click to reveal answer
beginner
How many lifetime elision rules does Rust have?
Rust has three main lifetime elision rules that guide how lifetimes are inferred in function signatures.
Click to reveal answer
intermediate
Explain the first lifetime elision rule.
If there is exactly one input lifetime, that lifetime is assigned to all output lifetimes.
Click to reveal answer
intermediate
What does the second lifetime elision rule state?
If there are multiple input lifetimes, but one of them is &self or &mut self, then the lifetime of self is assigned to all output lifetimes.
Click to reveal answer
intermediate
When do you need to explicitly write lifetime annotations in Rust functions?
You must write explicit lifetime annotations when the elision rules do not apply, such as when multiple input lifetimes exist without a self reference and the output lifetime is ambiguous.
Click to reveal answer
How many lifetime elision rules does Rust use to infer lifetimes?
A5
B1
C3
DNone
According to the first elision rule, if a function has one input lifetime, what happens to the output lifetime?
AIt must be explicitly annotated
BIt is ignored
CIt gets a static lifetime
DIt gets the same lifetime as the input
What special input does the second elision rule consider when assigning output lifetimes?
AAny reference
B&self or &mut self
CStatic lifetime
DMutable references only
When must you write explicit lifetime annotations in Rust functions?
AWhen elision rules do not clearly assign output lifetimes
BAlways, for every function
COnly for functions without inputs
DNever, Rust infers all lifetimes
Which of these is NOT a lifetime elision rule?
AIf multiple input lifetimes exist without self, assign output to the first input
BIf one input is &self or &mut self, assign its lifetime to output
CIf there is exactly one input lifetime, assign it to output
DIf no input lifetimes, output lifetime is static
Describe the three lifetime elision rules in Rust and give a simple example for each.
Think about function inputs and outputs and how Rust guesses lifetimes.
You got /4 concepts.
    Explain when and why you need to write explicit lifetime annotations instead of relying on elision.
    Consider functions with multiple references as inputs.
    You got /3 concepts.