Mutable references in Rust - Time & Space Complexity
When using mutable references in Rust, it's important to see how the program's steps grow as input gets bigger.
We want to know how the time to run changes when we change the size of the data we modify through mutable references.
Analyze the time complexity of the following code snippet.
fn increment_all(nums: &mut [i32]) {
for num in nums {
*num += 1;
}
}
fn main() {
let mut values = vec![1, 2, 3, 4, 5];
increment_all(&mut values);
}
This code increases each number in a list by one using a mutable reference to change the original data.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each element in the list to increment it.
- How many times: Once for each element in the list.
As the list gets bigger, the program spends more time because it changes each number one by one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 increments |
| 100 | 100 increments |
| 1000 | 1000 increments |
Pattern observation: The time grows directly with the number of items; doubling items doubles the work.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the number of elements you change.
[X] Wrong: "Using mutable references makes the code run faster because it changes data directly."
[OK] Correct: Mutable references let you change data safely, but the time depends on how many items you process, not just on using references.
Understanding how mutable references affect time helps you explain how your code handles data changes efficiently and safely.
"What if we changed the loop to only increment every other element? How would the time complexity change?"
Practice
&mut allow you to do in Rust?Solution
Step 1: Understand what
The&mutmeans&mutsymbol creates a mutable reference, which means you can change the value it points to without taking ownership.Step 2: Compare with other options
Options B and D describe immutable references or no changes allowed, and C talks about ownership transfer, which is different from mutable references.Final Answer:
Change the value it points to without taking ownership -> Option DQuick Check:
Mutable reference = change value without ownership [OK]
- Confusing mutable references with ownership transfer
- Thinking multiple mutable references are allowed simultaneously
- Believing mutable references prevent changes
num in Rust?Solution
Step 1: Identify the syntax for mutable references
In Rust, to create a mutable reference, you use&mutbefore the variable name.Step 2: Check each option
A creates an immutable reference, B dereferences the value, and D has incorrect syntax order.Final Answer:
let ref = &mut num; -> Option BQuick Check:
Mutable reference syntax = &mut variable [OK]
- Forgetting the 'mut' keyword after &
- Placing 'mut' before & incorrectly
- Using * instead of &mut for references
fn main() {
let mut x = 5;
let r = &mut x;
*r += 1;
println!("{}", x);
}Solution
Step 1: Understand the mutable reference usage
The variablexis mutable. A mutable referenceris created tox. The value pointed byris incremented by 1 using*r += 1;.Step 2: Determine the final value of
Sincexrpoints tox, incrementing*rchangesxfrom 5 to 6. The print statement outputs 6.Final Answer:
6 -> Option AQuick Check:
Mutable reference modifies original value = 6 [OK]
- Expecting original value unchanged
- Confusing reference with copy
- Thinking code causes compile error
fn main() {
let mut val = 10;
let r1 = &mut val;
let r2 = &mut val;
*r1 += 1;
*r2 += 1;
println!("{}", val);
}Solution
Step 1: Identify the mutable references
The code creates two mutable referencesr1andr2to the same variablevalat the same time.Step 2: Recall Rust's borrowing rules
Rust allows only one mutable reference at a time to prevent data races. Having two mutable references simultaneously causes a compile-time error.Final Answer:
Cannot have two mutable references to the same variable at the same time -> Option CQuick Check:
Only one mutable reference allowed at once [OK]
- Trying to create multiple mutable references simultaneously
- Thinking mutable references can be copied freely
- Ignoring Rust's borrowing rules
data using mutable references without causing a compile error?fn main() {
let mut data = 100;
let r1 = &data;
let r2 = &mut data;
*r2 += 50;
println!("{}", data);
}Solution
Step 1: Understand Rust's borrowing rules
Rust does not allow mutable and immutable references to the same variable at the same time. Here,r1is immutable andr2is mutable, causing a conflict.Step 2: Fix the code by removing the immutable reference
Removingr1allows only the mutable referencer2to exist, so modifyingdatathroughr2is safe and allowed.Final Answer:
Remove the immutable referencer1before creatingr2-> Option AQuick Check:
Mutable and immutable refs cannot coexist [OK]
- Trying to use mutable and immutable references simultaneously
- Changing mutable ref to immutable without reason
- Making variable immutable but still trying to mutate
Ready to prove it?
Pass the test and this pattern moves unknown
