I tried to implement a generic matrix product function which should work for all primitive types and the BigInt
/BigUint
types from the num_bigint
crate:
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() {}
I got the following error message:
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`
How can I implement the function for &T
in this case?
Shepmaster deems this question as duplicated, but it seems due to operator (AddAssign
or Mul
) applied on reference (&T
) require separate statement after where
keyword