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?