0
0
Rustprogramming~10 mins

Lifetimes in functions in Rust - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Lifetimes in functions
Function called with references
Check lifetime annotations
Compare input lifetimes
Valid
Return reference with correct lifetime
Function ends
This flow shows how Rust checks lifetime annotations in functions to ensure returned references are valid and safe.
Execution Sample
Rust
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() > y.len() { x } else { y }
}

let s1 = String::from("hello");
let s2 = "world!";
let result = longest(&s1, &s2);
This function returns the longest of two string slices, using lifetime annotations to ensure safety.
Execution Table
StepActionInput lifetimesComparisonReturn valueNotes
1Function longest called&'a str, &'a strCheck lifetimes 'a and 'aN/ABoth inputs have lifetime 'a
2Compare lengthss1.len()=5, s2.len()=65 > 6Return s2s2 is longer
3Return referenceReturn &'a strN/A&s2Return reference tied to lifetime 'a
4Assign to resultresult: &'a strN/A"world!"result holds reference to s2
5Function endsN/AN/AN/ALifetimes ensure no dangling refs
💡 Function returns reference with lifetime 'a, ensuring safety of returned reference
Variable Tracker
VariableStartAfter Step 2After Step 3Final
x&s1 ("hello")&s1 ("hello")&s1 ("hello")&s1 ("hello")
y&s2 ("world!")&s2 ("world!")&s2 ("world!")&s2 ("world!")
resultuninitializeduninitialized&s2 ("world!")&s2 ("world!")
Key Moments - 3 Insights
Why do we need to specify lifetime 'a in the function signature?
Because Rust needs to know that the returned reference lives at least as long as both input references. This is shown in the execution_table step 1 where lifetimes are checked.
What happens if the input references have different lifetimes?
Rust will require the returned reference to have the shorter lifetime of the inputs to avoid dangling references. This is implied in the comparison step in the execution_table.
Why can't we return a reference without lifetime annotations?
Without lifetime annotations, Rust cannot guarantee the returned reference is valid, so it will cause a compile error. This safety check is part of the flow in the concept_flow diagram.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 2, which string slice is longer?
As1 ("hello")
Bs2 ("world!")
CBoth are equal
DCannot determine
💡 Hint
Check the 'Comparison' column in step 2 of the execution_table
At which step is the returned reference assigned to the variable 'result'?
AStep 1
BStep 2
CStep 4
DStep 3
💡 Hint
Look at the 'Action' column in the execution_table for assignment details
If the input lifetimes were different, how would Rust determine the lifetime of the returned reference?
AIt uses the shorter lifetime
BIt uses the longer lifetime
CIt ignores lifetimes
DIt returns an owned String instead
💡 Hint
Refer to the key_moments explanation about lifetime comparisons
Concept Snapshot
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
  // returns longest string slice
}

- Lifetime 'a ties inputs and output
- Ensures returned ref lives long enough
- Prevents dangling references
- Compiler checks lifetimes at compile time
Full Transcript
This visual trace shows how Rust functions use lifetimes to ensure references returned are valid. The function longest takes two string slices with the same lifetime 'a and returns the longer one with that lifetime. Step by step, the function compares lengths, returns the correct reference, and assigns it to a variable. Lifetimes prevent unsafe references by tying the output lifetime to the inputs. If lifetimes differ, Rust uses the shorter one to keep safety. This prevents bugs and crashes from invalid memory access.