// 定义矩阵操作所需的trait
trait MatrixElement: Copy + Clone + std::ops::Mul<Output = Self> + std::ops::Add<Output = Self> {
fn zero() -> Self;
}
// 定义Matrix结构体
struct Matrix<T>
where
T: MatrixElement,
{
data: Vec<T>,
rows: usize,
cols: usize,
}
impl<T> Matrix<T>
where
T: MatrixElement,
{
// 构造函数
fn new(rows: usize, cols: usize) -> Self {
Matrix {
data: vec![T::zero(); rows * cols],
rows,
cols,
}
}
// 获取矩阵元素
fn get(&self, row: usize, col: usize) -> Option<&T> {
if row < self.rows && col < self.cols {
Some(&self.data[row * self.cols + col])
} else {
None
}
}
// 设置矩阵元素
fn set(&mut self, row: usize, col: usize, value: T) -> Option<()> {
if row < self.rows && col < self.cols {
self.data[row * self.cols + col] = value;
Some(())
} else {
None
}
}
// 转置矩阵
fn transpose(self) -> Matrix<T> {
let mut result = Matrix::new(self.cols, self.rows);
for i in 0..self.rows {
for j in 0..self.cols {
result.set(j, i, *self.get(i, j).unwrap()).unwrap();
}
}
result
}
// 矩阵乘法
fn multiply(&self, other: &Matrix<T>) -> Option<Matrix<T>> {
if self.cols != other.rows {
return None;
}
let mut result = Matrix::new(self.rows, other.cols);
for i in 0..self.rows {
for j in 0..other.cols {
let mut sum = T::zero();
for k in 0..self.cols {
sum = sum + self.get(i, k).unwrap() * other.get(k, j).unwrap();
}
result.set(i, j, sum).unwrap();
}
}
Some(result)
}
}
性能优化说明:
- 所有权:在
transpose
方法中,采用了self
参数,意味着原矩阵的所有权被转移,避免了重复的内存分配和拷贝。
- 生命周期:在
multiply
方法中,使用&self
和&other
引用,明确了矩阵在方法调用期间的生命周期,确保不会发生悬空引用。并且操作过程中直接操作矩阵内部的数据,避免了不必要的数据拷贝。
- 泛型trait限定:通过限定泛型类型参数
T
必须实现Copy
、Clone
、Mul
和Add
trait,并提供zero
方法,保证了矩阵操作的基本运算需求,同时Copy
trait 有助于减少数据拷贝。