Home > Software design >  Nested for loop in rust, modifying elements in a vector
Nested for loop in rust, modifying elements in a vector

Time:01-30

I am trying to create a nested loop in rust, that goes through a vector. Essentially, it looks like this:

fn main() {
    let v = vec![1, 2, 3];
    
    for i in &mut v {
        for j in &mut v {
            if i == j {
                *i = *j   1;
            }
        }
    }
    
    println!("{:?}", v);
}

However, this will not work; Rust cannot borrow as mutable more than once.

In my case, this the elements in the vector are structs that have non copy-able elements inside of them. How could rust go about doing something like this?

CodePudding user response:

You'll have to use indexing in this case as a work around, which will create more localized borrows and satisfy the borrow checker:

fn main() {
    let mut v = vec![1, 2, 3];

    for i in 0..v.len() {
        for j in 0..v.len() {
            if v[i] == v[j] {
                v[i] = v[j]   1;
            }
        }
    }

    println!("{:?}", v);
}

Output:

[4, 4, 4]

Playground

Here, only v[i] is borrowed mutably for a moment while it is assigned the value of v[j] 1.

  • Related