0
0
Rustprogramming~10 mins

Lifetimes in structs in Rust - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Lifetimes in structs
Define struct with lifetime
Create instance with reference
Use instance safely
Lifetime ends when references drop
Memory is safe, no dangling refs
This flow shows how a struct with a lifetime parameter holds references safely until they go out of scope.
Execution Sample
Rust
struct Holder<'a> {
    value: &'a str,
}

fn main() {
    let text = String::from("hello");
    let h = Holder { value: &text };
    println!("{}", h.value);
}
This code defines a struct with a lifetime, creates an instance holding a reference, and prints the referenced string.
Execution Table
StepActionVariable StatesLifetime CheckOutput
1Define struct Holder with lifetime 'aHolder<'a> definedNo references yet
2Create String text = "hello"text = "hello"text owns data
3Create Holder h with value = &texth.value points to texth.value lifetime <= text lifetime
4Print h.valueh.value = "hello"Reference validhello
5End of main, text and h go out of scopetext and h droppedReferences cleaned safely
💡 Execution ends as main function scope ends, all references are valid and dropped safely.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
textuninitialized"hello""hello""hello"dropped
h.valueuninitializeduninitialized&text ("hello")&text ("hello")dropped
Key Moments - 3 Insights
Why do we need to specify a lifetime 'a in the struct definition?
Because the struct holds a reference, Rust needs to know how long that reference is valid to prevent dangling pointers. See execution_table step 3 where h.value points to text.
What happens if the referenced data (text) goes out of scope before the struct instance?
Rust will give a compile-time error because the struct's reference would be invalid. In the execution_table, step 5 shows both text and h go out of scope safely.
Can the struct hold a reference without a lifetime annotation?
No, Rust requires explicit lifetime annotations on structs holding references to ensure safety, as shown in step 1.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 3, what does h.value point to?
AThe String text containing "hello"
BAn uninitialized variable
CA copy of the string "hello"
DA dangling pointer
💡 Hint
Check the Variable States column at step 3 in execution_table.
At which step does Rust ensure the reference lifetime is valid?
AStep 1
BStep 4
CStep 3
DStep 5
💡 Hint
Look at the Lifetime Check column in execution_table.
If text was dropped before h, what would happen?
AProgram runs normally
BCompile-time error due to invalid reference
CRuntime panic
Dh.value becomes a copy of text
💡 Hint
Refer to key_moments about lifetime safety and execution_table step 5.
Concept Snapshot
struct Holder<'a> { value: &'a str }  
- 'a is a lifetime parameter
- Ensures reference inside struct lives long enough
- Rust checks lifetimes at compile time
- Prevents dangling references
- Use when struct holds references
Full Transcript
This example shows how Rust uses lifetimes in structs to keep references safe. We define a struct Holder with a lifetime 'a to hold a reference to a string slice. We create a String variable text and then create an instance h of Holder that holds a reference to text. Rust ensures that h's reference does not outlive text. When we print h.value, it safely shows "hello". At the end of main, both text and h go out of scope, and Rust cleans up safely without any dangling references. Lifetimes prevent errors by making sure references inside structs are valid as long as needed but no longer.