Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Rust iterate over borrowed mutable reference

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading