0
0
Rustprogramming~10 mins

Variable lifetime basics in Rust - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Variable lifetime basics
Declare variable
Variable is valid
Use variable
Scope ends
Variable is dropped
Memory freed
This flow shows how a variable is created, used, and then dropped when its scope ends, freeing memory.
Execution Sample
Rust
fn main() {
    let x = 5;
    println!("x = {}", x);
}
This code declares a variable x, uses it to print, then x is dropped at the end of main.
Execution Table
StepActionVariable x StateOutput
1Declare x = 5x = 5 (valid)
2Print xx = 5 (valid)x = 5
3End of main scopex dropped (invalid)
💡 Variable x is dropped after main ends, memory is freed.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3 (End)
xundefined5 (valid)5 (valid)dropped (invalid)
Key Moments - 2 Insights
Why can't we use variable x after step 3?
Because at step 3, the scope ends and x is dropped, so it no longer exists (see execution_table step 3).
Is the variable x valid during the print statement?
Yes, at step 2 x is still valid and holds the value 5, so it can be used safely.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the state of x at step 2?
Ax is valid and equals 5
Bx is dropped and invalid
Cx is uninitialized
Dx is zero
💡 Hint
Check the 'Variable x State' column at step 2 in the execution_table.
At which step does variable x get dropped?
AStep 1
BStep 2
CStep 3
DNever
💡 Hint
Look at the 'Action' and 'Variable x State' columns in execution_table for when x becomes invalid.
If we moved the print statement outside main, what would happen?
Ax would still be valid and print 5
BCompilation error because x is out of scope
Cx would print 0 by default
DProgram would crash at runtime
💡 Hint
Variables in Rust are valid only within their scope; see variable_tracker for scope lifetime.
Concept Snapshot
Variable lifetime in Rust:
- Variables are valid within their scope.
- When scope ends, variables are dropped.
- Dropped variables free memory.
- Using variables after drop causes errors.
- Always use variables within their lifetime.
Full Transcript
This visual trace shows how a variable in Rust is declared, used, and then dropped when its scope ends. The variable x is created with value 5, used in a print statement, and then dropped at the end of the main function. After dropping, x no longer exists and cannot be used. This demonstrates Rust's variable lifetime rules: variables live only within their scope and are automatically cleaned up when the scope ends.