<分区>
我正在用 Rust 实现矩阵。代码针对示例进行了改编,但可能存在一些小错误:
#[derive(Debug, PartialEq)]
pub struct Matrix<T> {
inner: Vec<Vec<T>>,
}
impl<T> Matrix<T> {
pub fn dim(&self) -> (usize, usize) {
if self.inner.len() == 0 {
(0, 0)
} else {
(self.inner.len(), self.inner[0].len())
}
}
}
我想获得矩阵的象限:
+----+----+
| Q1 | Q2 |
+----+----+
| Q3 | Q4 |
+----+----+
我引入了Slice
和SliceMut
结构来借用矩阵的一部分:
pub struct Slice<'a, T: 'a> {
matrix: &'a Matrix<T>,
start: (usize, usize),
end: (usize, usize),
}
pub struct SliceMut<'a, T: 'a> {
matrix: &'a mut Matrix<T>,
start: (usize, usize),
end: (usize, usize),
}
现在我要实现两个功能:
quadrants
- 得到一个包含四个切片的元组quadrants_mut
- 获取包含四个可变切片的元组
我不能在 quadrants_mut
中多次可变地借用一个矩阵:
fn quadrants_mut<'a, T>(matrix: &'a mut Matrix<T>) -> (SliceMut<'a, T>, SliceMut<'a, T>, SliceMut<'a, T>, SliceMut<'a, T>) {
let (rows, cols) = matrix.dim();
let mid_rows = rows / 2;
let mid_cols = cols / 2;
let a = SliceMut { matrix: matrix, start: (0, 0), end: (mid_rows, mid_cols) };
let b = SliceMut { matrix: matrix, start: (0, mid_rows), end: (mid_cols, cols) };
let c = SliceMut { matrix: matrix, start: (mid_rows, rows), end: (0, mid_cols) };
let d = SliceMut { matrix: matrix, start: (mid_rows, rows), end: (mid_cols, cols) };
(a, b, c, d)
}
当我尝试编译它时,出现错误:
error[E0499]: cannot borrow `*matrix` as mutable more than once at a time
--> src/matrix/slice.rs:62:13
|
59 | let a = SliceMut { matrix: matrix, start: (0, 0), end: (mid_rows, mid_cols) };
| ------ first mutable borrow occurs here
...
60 | let b = SliceMut { matrix: matrix, start: (0, mid_rows), end: (mid_cols, cols) };
| ^^^^^^ second mutable borrow occurs here
...
66 | }
我试图可变地借用一个矩阵四次。我应该如何更改代码以使其通过编译?