Mutable variables in Rust - Time & Space Complexity
Let's see how using mutable variables affects how long a program takes to run.
We want to know how the program's steps grow when we change the input size.
Analyze the time complexity of the following code snippet.
fn sum_numbers(n: u32) -> u32 {
let mut total = 0;
for i in 1..=n {
total += i;
}
total
}
This code adds numbers from 1 up to n using a mutable variable to keep the running total.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding each number to the total inside the loop.
- How many times: Exactly n times, once for each number from 1 to n.
Each time n gets bigger, the loop runs more times, so the work grows steadily.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The number of steps grows directly with n; doubling n doubles the work.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the size of the input.
[X] Wrong: "Using a mutable variable makes the program faster or slower in a way that changes the time complexity."
[OK] Correct: The mutable variable just holds the running total; it doesn't add extra loops or steps. The main factor is how many times the loop runs.
Understanding how loops and variables affect time helps you explain your code clearly and shows you know what makes programs faster or slower.
"What if we replaced the loop with recursion that sums numbers? How would the time complexity change?"
Practice
Solution
Step 1: Understand variable declaration in Rust
Rust usesletto declare variables, but by default they are immutable.Step 2: Identify how to make variables mutable
Addingmutafterletmakes the variable mutable.Final Answer:
mut -> Option DQuick Check:
Uselet mutfor mutable variables [OK]
let mut makes variables changeable [OK]- Using 'var' instead of 'mut'
- Forgetting 'mut' and expecting change
- Using 'let' alone for mutable variables
x with value 5 in Rust?Solution
Step 1: Recall correct order of keywords
In Rust,letcomes first, thenmutto mark mutability.Step 2: Check each option's syntax
let mut x = 5; useslet mut x = 5;which is correct. Others have wrong order or invalid keywords.Final Answer:
let mut x = 5; -> Option AQuick Check:
Correct syntax islet mut variable = value;[OK]
let mut in that order [OK]- Swapping 'mut' and 'let'
- Using 'var' instead of 'let'
- Omitting 'mut' when variable changes
fn main() {
let mut count = 1;
count = count + 2;
println!("{}", count);
}Solution
Step 1: Understand variable initialization and mutation
The variablecountstarts at 1 and is mutable.Step 2: Calculate the new value after addition
Adding 2 to 1 gives 3, socountbecomes 3.Final Answer:
3 -> Option AQuick Check:
Mutable variable updated correctly outputs 3 [OK]
- Expecting original value without mutation
- Thinking code causes error without 'mut'
- Confusing output with variable name
fn main() {
let x = 10;
x = 20;
println!("{}", x);
}Solution
Step 1: Check variable mutability
Variablexis declared withoutmut, so it is immutable.Step 2: Analyze reassignment attempt
Assigningx = 20;tries to change an immutable variable, causing a compile error.Final Answer:
Cannot assign twice to immutable variable x -> Option CQuick Check:
Immutable variables cannot be reassigned [OK]
mut to allow variable reassignment [OK]- Ignoring need for 'mut' to reassign
- Thinking println! needs semicolon error
- Assuming variable is undeclared
fn main() {
let mut counter = 0;
increment(&mut counter);
increment(&mut counter);
println!("{}", counter);
}
fn increment(count: &mut i32) {
*count += 1;
}Solution
Step 1: Check mutability of counter
Counter is declared mutable withlet mut counter = 0;.Step 2: Understand function parameter and mutation
Functionincrementtakes a mutable reference and increases the value by 1 each call.Step 3: Count increments and final output
Called twice, counter increases from 0 to 2, then printed.Final Answer:
Code compiles and prints 2 -> Option BQuick Check:
Mutable variable with mutable reference updates correctly [OK]
let mut and mutable references to update variables [OK]- Forgetting 'mut' on variable or reference
- Passing immutable reference to function
- Expecting counter to update without mutable reference
Ready to prove it?
Pass the test and this pattern moves unknown
