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.
fn main() {
let x = 5;
println!("x = {}", x);
}| Step | Action | Variable x State | Output |
|---|---|---|---|
| 1 | Declare x = 5 | x = 5 (valid) | |
| 2 | Print x | x = 5 (valid) | x = 5 |
| 3 | End of main scope | x dropped (invalid) |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 (End) |
|---|---|---|---|---|
| x | undefined | 5 (valid) | 5 (valid) | dropped (invalid) |
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.