使用定义为 的矩阵(多维固定大小的数组)[[f64; 4]; 4],是否可以交换两个值?
std::mem::swap(&mut matrix[i][k], &mut matrix[k][l]);
Run Code Online (Sandbox Code Playgroud)
给出错误:
std::mem::swap(&mut matrix[i][k], &mut matrix[k][l]);
Run Code Online (Sandbox Code Playgroud)
我能弄清楚如何实现这一点的唯一方法是使用临时值,例如:
macro_rules! swap_value {
($a_ref:expr, $b_ref:expr) => {
{
let t = *$a_ref;
*$a_ref = *$b_ref;
*$b_ref = t;
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后使用:
swap_value!(&mut matrix[i][k], &mut matrix[maxj][k]);
Run Code Online (Sandbox Code Playgroud)
有更好的选择吗?
您将需要使用 来分割外层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`!
}
Run Code Online (Sandbox Code Playgroud)
在最一般的情况下,您可能需要添加一些代码来确定拆分的位置和顺序。