Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rust iterate over borrowed mutable reference

Tags:

foreach

rust

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?

like image 788
gurkensaas Avatar asked Jun 27 '26 12:06

gurkensaas


1 Answers

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]
}
like image 137
isaactfa Avatar answered Jun 29 '26 13:06

isaactfa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!