How to swap inner elements of multi dimensional array?


#1

This code emits an error because we cannot borrow m as mutable more than once.

fn main() {
    let mut m = [
        [0, 1, 2],
        [3, 4, 5],
        [6, 7, 8]
    ];
    for i in 0..3 {
        for j in 0..i {
            std::mem::swap(&mut m[i][j], &mut m[j][i]);
        }
    }
}
error[E0499]: cannot borrow `m` as mutable more than once at a time
 --> main.rs:9:47
  |
9 |             std::mem::swap(&mut m[i][j], &mut m[j][i]);
  |                                 -             ^      - first borrow ends here
  |                                 |             |
  |                                 |             second mutable borrow occurs here
  |                                 first mutable borrow occurs here

error: aborting due to previous error

If the type of objective elements is in Copy trait, we can write as following.

let t = m[i][j];
m[i][j] = m[j][i];
m[j][i] = t;

But is there more generic way?


#2

You could use m.split_at_mut(i), then swap from the distinct parts.


#3

So the code will be following:

fn main(){
    let mut m = [
        [0, 1, 2],
        [3, 4, 5],
        [6, 7, 8]
    ];
    for i in 0..3 {
        for j in 0..i {
            let (mut a, mut b) = m.split_at_mut(i);
            std::mem::swap(&mut a[j][i], &mut b[0][j]);
        }
    }
    println!("{:?}", m);
}

and it works. Thank you!