I am trying to iterate over an array, mutably borrowing its elements one by one. In each iteration, I want to use the results from the previous one. I wrote the code like the one below:
fn main() {
let mut arr: [Vec<u32>; 3] = [vec![1, 2, 3], Vec::new(), Vec::new()];
for i in 1..3usize {
let prev_vec: &Vec<u32> = &arr[i - 1];
for prev_num in prev_vec {
arr[i].push(prev_num * 2);
}
}
dbg!(arr);
}
However, it seems that in the line let prev_vec: &Vec<u32> = &arr[i - 1]; instead of borrowing only the vector, the whole array gets marked as borrowed. The compiler errors is
--> example.rs:6:13
|
4 | let prev_vec: &Vec<u32> = &arr[i - 1];
| ----------- immutable borrow occurs here
5 | for prev_num in prev_vec {
| -------- immutable borrow later used here
6 | arr[i].push(prev_num * 2);
| ^^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
Why does the borrow checker assume the whole array is borrowed? How can I rewrite this code, so it is accepted by the compiler?