如何要求对泛型类型的引用实现特征?

时间:2018-05-30 05:01:40

标签: rust

我尝试实现一个通用矩阵产品函数,它应该适用于所有原始类型和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}后单独声明关键字

0 个答案:

没有答案