Variable lifetime basics in Rust - Time & Space Complexity
When we write Rust code, variables only exist for a certain time called their lifetime.
We want to understand how the time a program runs changes as variables live and get used.
Analyze the time complexity of the following code snippet.
fn sum_values(values: &[i32]) -> i32 {
let mut total = 0;
for &value in values {
total += value;
}
total
}
fn main() {
let numbers = vec![1, 2, 3, 4, 5];
let result = sum_values(&numbers);
println!("Sum: {}", result);
}
This code adds up numbers in a list, using a variable that lives during the loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number in the list.
- How many times: Once for each number in the input list.
As the list gets bigger, the loop runs more times, adding each number once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 additions |
| 100 | About 100 additions |
| 1000 | About 1000 additions |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to run grows in a straight line as the input list gets bigger.
[X] Wrong: "The variable lifetime makes the program slower because it lasts longer."
[OK] Correct: The variable lifetime just means how long the variable exists in memory, not how many times the code runs. The speed depends on how many times the loop runs, not how long variables live.
Understanding how variable lifetime relates to loops helps you explain how your code runs efficiently and safely in Rust.
"What if we changed the loop to call a function inside that also loops over the input? How would the time complexity change?"
Practice
Solution
Step 1: Define lifetime and evaluate options
In Rust, lifetime refers to how long a reference is valid and safe to use. Only 'How long a reference remains valid in the program' correctly describes it; B is size, C is usage count, D is type.Final Answer:
How long a reference remains valid in the program -> Option AQuick Check:
Lifetime = reference validity duration [OK]
- Confusing lifetime with variable size
- Thinking lifetime counts usage times
- Mixing lifetime with variable type
'a for a reference argument in Rust?Solution
Step 1: Verify lifetime annotation syntax and check options
Rust requires lifetime parameters declared with'abefore 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.Final Answer:
fn example<'a>(x: &'a i32) -> &'a i32 { x } -> Option CQuick Check:
Lifetime syntax = fn name<'a>(x: &'a Type) -> &'a Type [OK]
- Placing lifetime after type instead of before
- Omitting lifetime on input or output references
- Using lifetime without declaring it
fn main() {
let mut r;
{
let x = 5;
r = &x;
}
println!("{}", r);
}Solution
Step 1: Analyze scopes and reference lifetime
x goes out of scope at end of inner block, but r references it and lives longer, violating Rust's lifetime rules, resulting in compilation error.Final Answer:
Compilation error due to lifetime mismatch -> Option BQuick Check:
Reference lifetime must not outlive data [OK]
- Assuming code prints 5 without error
- Expecting runtime panic instead of compile error
- Ignoring inner block scope
fn longest(x: &str, y: &str) -> &str {
if x.len() > y.len() { x } else { y }
}Solution
Step 1: Examine function signature and Rust lifetime rules
The function returns a reference to one of the inputs without lifetime annotations, preventing Rust from verifying safety. Annotations like <'a> are required on params and return.Final Answer:
Missing lifetime annotations on parameters and return type -> Option AQuick Check:
Return references need lifetime annotations [OK]
- Thinking &str vs String causes error
- Believing function should return length
- Assuming no error without lifetimes
Holder is valid?
struct Holder<'a> {
value: &'a str,
}
fn create_holder(s: &str) -> Holder {
Holder { value: s }
}Solution
Step 1: Match function signature to struct lifetime parameter
Holder<'a> ties value's lifetime to 'a. Function must declare 'a, use on s: &'a str, return Holder<'a>. D correct; A lacks fn 'a decl, B/C mismatch lifetimes.Final Answer:
fn create_holder<'a>(s: &'a str) -> Holder<'a> { Holder { value: s } } -> Option DQuick Check:
Function lifetimes must match struct lifetimes [OK]
- Omitting lifetime on function signature
- Using lifetime only on return or input, not both
- Assuming struct lifetime is optional
Ready to prove it?
Pass the test and this pattern moves unknown
