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]);
有没有更好的选择?
值得强调的是,在分割之后,外层在'y'中被索引为0。这是一个很容易犯的错误。 –