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?
If you want to mutate the Vec, the correct way is to iterate over it mutably instead of immutably:
fn foo(vec: &mut Vec<i32>) {
// note the `iter_mut` here:
for element in vec.iter_mut() {
// Some checks here
// element now has type `&mut i32` and we can mutate it directly.
*element *= 2;
}
}
fn main() {
let mut bar: Vec<i32> = vec![1, 2, 3];
foo(&mut bar);
println!("{:?}", bar); // [2, 4, 6]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With