0
0
Rustprogramming~10 mins

Lifetime annotations in Rust - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Lifetime annotations
Start: Define function with lifetimes
Input references with lifetimes
Check lifetime constraints
Valid
Return reference with correct lifetime
End
The flow shows how Rust checks lifetime annotations on references to ensure safe borrowing and returns references with correct lifetimes.
Execution Sample
Rust
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() >= y.len() { x } else { y }
}

fn main() {
    let s1 = String::from("hello");
    let s2 = "world";
    let result = longest(&s1, &s2);
    println!("{}", result);
}
This code defines a function that returns the longest of two string slices with lifetime annotations ensuring safety.
Execution Table
StepActionInput lifetimesCheckReturn valueExplanation
1Call longest(&s1, &s2)'a = lifetime of s1 and s2 referencesBoth inputs have lifetime 'aN/AFunction called with two string slices having lifetime 'a
2Compare lengthsx.len()=5, y.len()=5No lifetime conflictN/ALengths compared, no lifetime issues
3Return referenceReturn &s1 or &s2Return lifetime 'a&s1Returns reference with lifetime 'a, here &s1 chosen
4Print resultresult lifetime 'aValid lifetimehelloPrints the longest string slice safely
5End mainAll lifetimes validProgram endsN/AProgram terminates successfully
💡 Execution stops after printing the longest string slice with valid lifetime annotations.
Variable Tracker
VariableStartAfter 1After 2After 3Final
s1String::from("hello")N/AN/AN/AN/A
s2"world"N/AN/AN/AN/A
x&s1 (lifetime 'a)&s1&s1&s1&s1
y&s2 (lifetime 'a)&s2&s2&s2&s2
resultN/AN/AN/A&s1&s1
Key Moments - 3 Insights
Why do we need to specify the lifetime 'a in the function signature?
Because Rust needs to know that the returned reference will live at least as long as both input references, ensuring no dangling references. See execution_table step 3 where the return lifetime 'a is enforced.
What happens if the input references have different lifetimes?
Rust will raise a compile-time error because it cannot guarantee the returned reference is valid. The function requires both inputs to share the same lifetime 'a as shown in execution_table step 1.
Why does the function return &s1 instead of &s2 when lengths are equal?
The function returns the first reference if lengths are equal due to the if condition. This choice does not affect lifetime correctness, as both have lifetime 'a (execution_table step 3).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 3, what lifetime is assigned to the returned reference?
A'static
B'a
C'b
DNo lifetime
💡 Hint
Check the 'Return value' and 'Check' columns in step 3 of execution_table.
At which step does the program compare the lengths of the two string slices?
AStep 2
BStep 1
CStep 3
DStep 4
💡 Hint
Look at the 'Action' column in execution_table to find when lengths are compared.
If s2 had a shorter lifetime than s1, what would happen during the function call?
AFunction would compile and run normally
BThe function would return a reference with lifetime of s1
CRust would raise a compile-time error due to lifetime mismatch
DThe function would return a reference with lifetime of s2
💡 Hint
Refer to key_moments about lifetime mismatches and execution_table step 1.
Concept Snapshot
Lifetime annotations in Rust:
- Use syntax fn foo<'a>(x: &'a T) -> &'a T
- They tell Rust how long references live
- Ensure returned references don't outlive inputs
- Prevent dangling references and memory errors
- Lifetimes must be consistent across inputs and outputs
Full Transcript
This visual execution trace shows how Rust uses lifetime annotations to ensure safe borrowing. The function 'longest' takes two string slices with the same lifetime 'a and returns a reference with that lifetime. The execution steps show calling the function, comparing string lengths, returning a reference, and printing the result. Variables track the references and their lifetimes. Key moments clarify why lifetimes are needed and what happens if lifetimes differ. The quiz tests understanding of lifetime assignment, execution steps, and error conditions. The snapshot summarizes lifetime annotation syntax and purpose.