我尝试实现一个通用矩阵产品函数,它应该适用于所有原始类型和BigInt
crate中的BigUint
/ num_bigint
类型:
extern crate num_bigint;
extern crate num_traits;
use num_traits::identities::Zero;
use std::ops::{AddAssign, Mul};
#[derive(Debug, Clone)]
struct Matrix<T> {
n: usize,
m: usize,
data: Vec<Vec<T>>,
}
fn m_prd<T>(a: &Matrix<T>, b: &Matrix<T>) -> Matrix<T>
where
T: Clone + AddAssign + Mul<Output = T> + Zero,
{
let n = a.n;
let p = b.n;
let m = b.m;
let mut c = Matrix {
n: n,
m: m,
data: vec![vec![T::zero(); m]; n],
};
for i in 0..n {
for j in 0..m {
for k in 0..p {
c.data[i][j] += &a.data[i][k] * &b.data[k][j];
}
}
}
c
}
fn main() {}
我收到以下错误消息:
error[E0369]: binary operation `*` cannot be applied to type `&T`
--> src/main.rs:29:33
|
29 | c.data[i][j] += &a.data[i][k] * &b.data[k][j];
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: an implementation of `std::ops::Mul` might be missing for `&T`
在这种情况下如何实现&T
的功能?
Shepmaster将此问题视为duplicated,但似乎由于在引用(AddAssign
)上应用的运算符(Mul
或&T
)需要在{{1}后单独声明关键字