I wanted a function to control and change a vector in rust. Here is a simplified version:
fn foo(vec: &mut Vec<i32>) {
for (i, element) in vec.iter().enumerate() {
// Some checks here
vec[(*element) as usize] = i as i32;
}
}
fn main() {
let mut bar: Vec<i32> = vec![1, 0, 2];
foo(&mut bar);
}
This code does not compile because there is both an immutable and a mutable borrow of vec in foo. I tried getting around this by copying vec to a separate copy, which didn’t work and also wouldn’t have been very pretty. What is the correct way to do this?
>Solution :
You can avoid borrowing the whole Vec by using index access like this:
fn foo(vec: &mut Vec<i32>) {
for index in 0..vec.len() {
let element = vec[index];
if element <= 0 {
continue;
}
vec[index] = index as i32;
}
}
fn main() {
let mut bar: Vec<i32> = vec![1, 0, 2];
foo(&mut bar);
println!("{:?}", bar)
}