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.
'a for a reference argument in Rust?'a before the function and used in references as &'a i32. A correctly declares and uses 'a for input/output. B misplaces after type, C lacks annotations, D misses on input.fn main() {
let mut r;
{
let x = 5;
r = &x;
}
println!("{}", r);
}fn longest(x: &str, y: &str) -> &str {
if x.len() > y.len() { x } else { y }
}Holder is valid?
struct Holder<'a> {
value: &'a str,
}
fn create_holder(s: &str) -> Holder {
Holder { value: s }
}Pass the test and this pattern moves unknown