use std::ops::Add;
// 定义泛型结构体Matrix
struct Matrix<T>
where
T: Add<Output = T> + Clone,
{
data: Vec<Vec<T>>,
}
// 实现 + 运算符重载
impl<T> Add for Matrix<T>
where
T: Add<Output = T> + Clone,
{
type Output = Result<Matrix<T>, String>;
fn add(self, other: Matrix<T>) -> Self::Output {
if self.data.len() != other.data.len() || self.data[0].len() != other.data[0].len() {
return Err("矩阵维度不一致".to_string());
}
let mut result_data = Vec::new();
for (i, row) in self.data.iter().enumerate() {
let mut new_row = Vec::new();
for (j, elem) in row.iter().enumerate() {
let new_elem = elem.clone() + other.data[i][j].clone();
new_row.push(new_elem);
}
result_data.push(new_row);
}
Ok(Matrix { data: result_data })
}
}