Fix a loop that pushes into the Vec it iterates over (E0502)
add_doubles should append, for every even number already in nums, its double to the end of the same vector. The code does not compile: the compiler reports error[E0502]: cannot borrow `*nums` as mutable because it is also borrowed as immutable. Explain why the borrow checker rejects it, and rewrite the function.
Requirements:
- Keep the signature;
[1, 2, 3, 4]becomes[1, 2, 3, 4, 4, 8]. - Examine only the original elements: the appended doubles are not doubled again.
- No
unsafeand nocloneof the whole vector.
fn add_doubles(nums: &mut Vec<i32>) {
for n in nums.iter() {
if n % 2 == 0 {
nums.push(n * 2);
}
}
}Find and fix the bug.
nums.iter() keeps the vector borrowed for the whole loop, while push needs &mut and may reallocate the buffer the iterator reads. Collect the doubles first and extend afterwards, or index over 0..len fixed beforehand.
- Thinking
iter_mut()allows pushing into the vector during the loop - Blaming the reference type of the loop variable instead of the borrow on the vector
- Forgetting that
pushmay move the buffer, which is why the rejection is necessary
- Why does
nums.push(nums.len() as i32)compile although it reads and writesnums? - How would the fix change if the loop had to remove the odd elements instead?
The loop for n in nums.iter() holds a shared reference to the vector while it runs, and push needs &mut. The rule is not pedantry: when the buffer is full, push allocates a new one, moves the elements and frees the old one, and the iterator would go on reading freed memory. There are two fixes: leave the vector alone while it is being iterated, or iterate without an iterator.
fn add_doubles(nums: &mut Vec<i32>) {
// collect first, then append: the iterator's borrow ends before extend
let extra: Vec<i32> = nums.iter().filter(|n| *n % 2 == 0).map(|n| n * 2).collect();
nums.extend(extra);
}
fn add_doubles_by_index(nums: &mut Vec<i32>) {
// the length is fixed before the loop, so the new elements are not examined
let len = nums.len();
for i in 0..len {
if nums[i] % 2 == 0 {
nums.push(nums[i] * 2);
}
}
}
fn main() {
let mut nums = vec![1, 2, 3, 4];
add_doubles(&mut nums);
let mut more = vec![1, 2, 3, 4];
add_doubles_by_index(&mut more);
println!("{nums:?} {more:?}"); // [1, 2, 3, 4, 4, 8] [1, 2, 3, 4, 4, 8]
}The first version costs one temporary vector and reads like the task statement. The second holds no references to elements at all: nums[i] copies an i32, and push(nums[i] * 2) compiles thanks to two-phase borrows — the argument is evaluated before the &mut for push takes effect. iter_mut() does not help: a mutable iterator holds the vector too, and a push inside the loop becomes E0499.