2016-11-29 16 views
3

使用定義爲[[f64; 4]; 4]的矩陣(多維固定大小數組),是否可以交換兩個值?如何從Rust中的多維數組中交換值?

std::mem::swap(&mut matrix[i][k], &mut matrix[k][l]); 

給出了錯誤:

error[E0499]: cannot borrow `matrix[..][..]` as mutable more than once at a time 
    --> math_matrix.rs:100 
    | 
100 | std::mem::swap(&mut matrix[i][j], &mut matrix[k][l]); 
    |      ------------  ^^^^^^^^^^^^^^^- first borrow ends here 
    |      |     | 
    |      |     second mutable borrow occurs here 
    |      first mutable borrow occurs here 

我能想出如何做到這一點的唯一方法是使用一個臨時的值,例如:

macro_rules! swap_value { 
    ($a_ref:expr, $b_ref:expr) => { 
     { 
      let t = *$a_ref; 
      *$a_ref = *$b_ref; 
      *$b_ref = t; 
     } 
    } 
} 

然後使用:

swap_value!(&mut matrix[i][k], &mut matrix[maxj][k]); 

有沒有更好的選擇?

回答

2

您需要使用split_at_mut拆分外層。這就造成了兩個不相交的可變引用,然後可以單獨交換:

use std::mem; 

fn main() { 
    let mut matrix = [[42.0f64; 4]; 4]; 

    // instead of 
    // mem::swap(&mut matrix[0][1], &mut b[2][3]); 

    let (x, y) = matrix.split_at_mut(2); 
    mem::swap(&mut x[0][1], &mut y[0][3]); 
    //        ^-- Note that this value is now `0`! 
} 

在最一般的情況下,你可能需要添加一些代碼,找出哪裏拆分和順序。

+1

值得強調的是,在分割之後,外層在'y'中被索引爲0。這是一個很容易犯的錯誤。 –