1

I am trying to update elements of a vector knowing where each other is, i.e. test all pairs of elements (unordered), while changing them. So I started naively writing this:

for x in &mut v {
    for y in &mut v {
        // ...
    }
}

But I cannot mutably borrow the vector twice, plus, I could simply avoid a lot of iterations, writing this:

for x in 0..v.len() - 1 {
    for y in x..v.len() - 1 {
        let mut xc = &mut v[x];
        let yc = &v[y];
        // ...
    }
}

This doesn't work, because I borrow an immutable and a mutable reference! How can I write this basic kind of loop? (I do need the mutability for at least one of the elements.)

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Creart
  • 146
  • 1
  • 10
  • 1
    A simple and straightforward option is for the code in `// ...` to work with indices `x` and `y`, i.e. refrain from creating long-lived references to individual vector elements in the first place. – user4815162342 May 03 '20 at 19:18

1 Answers1

1

The concept of ownership will not let you borrow the same data mutably and immutably, so in safe Rust there is no possible solution to get the data at a certain index as an mutable and immutable reference.

This is probably not what you need anyway. Rust contains a feature that allows you to access multiple indexes in a slice:

fn main() {
    let mut v = vec![1, 2, 3];
    let len = v.len();
    for x in 0..len - 1 {
        let (first, second) = v.split_at_mut(x + 1);
        let xc = &mut first[x];
        *xc = *xc + 1; //some code that uses xc and yc if y == x
        for yc in second {
            *xc = *yc + 1; //some code that uses xc and yc if y > x
        }
    }
}

*xc = *yc + 1 is some example code that uses the references xc and yc. Note that the case where x == y must be handled separately.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
CoronA
  • 7,717
  • 2
  • 26
  • 53