繁体   English   中英

实现特征时类型不匹配

[英]Mismatched types when implementing a trait

要学习Rust,我正在构建自己的Matrix类。 我对Add trait的实现如下:

impl<T: Add> Add for Matrix<T>
{
    type Output = Matrix<T>;

    fn add(self, _rhs: Matrix<T>) -> Matrix<T>
    {
        assert!(self.rows == _rhs.rows && self.cols == _rhs.cols,
                "attempting to add matrices of different sizes");

        let mut res: Matrix<T> = Matrix::<T>{
            rows: self.rows,
            cols: self.cols,
            data : Vec::<T>::with_capacity(self.rows * self.cols),
        };

        for i in 0..self.rows*self.cols{
            res.data.push(self.data[i] + _rhs.data[i]);
        }
        res
   }
}

但我得到以下错误

       Compiling matrix v0.1.0 (file://~/soft/rust/projects/matrix)
src/lib.rs:35:27: 35:54 error: mismatched types:
 expected `T`,
    found `<T as core::ops::Add>::Output`
(expected type parameter,
    found associated type) [E0308]
src/lib.rs:35             res.data.push(self.data[i] + _rhs.data[i]);
                                        ^~~~~~~~~~~~~~~~~~~~~~~~~~~

通过错误报告,我想我需要指出其他地方T实现了Add特性,但是在我尝试执行此操作的任何地方,我都会得到相同的错误或解析错误。

我对Matrix的定义是

pub struct Matrix<T> {
    pub rows: usize,
    pub cols: usize,
    pub data: Vec<T>,
}

使用T: Add表示您可以写T + T ,但它不会对由此产生的类型施加任何限制,特别是可能不是T 您依靠它为T能够返回Matrix<T>

一种方法是要求T: Add<Output = T> ,以便T + T返回T

impl<T: Add<Output = T>> Add for Matrix<T> {
    ...
}

另一种方法是改为使用T要提供的任何输出:即,您的加法将返回Matrix<T::Output>

impl<T: Add> Add for Matrix<T>
{
    type Output = Matrix<T::Output>;

    fn add(self, _rhs: Matrix<T>) -> Matrix<T::Output>
    {
        assert!(self.rows == _rhs.rows && self.cols == _rhs.cols,
                "attempting to add matrices of different sizes");

        let mut res = Matrix {
            rows: self.rows,
            cols: self.cols,
            data : Vec::with_capacity(self.rows * self.cols),
        };

        for i in 0..self.rows*self.cols{
            res.data.push(self.data[i] + _rhs.data[i]);
        }
        res
   }
}

但是,这两个都遇到问题:

<anon>:23:27: 23:39 error: cannot move out of indexed content
<anon>:23             res.data.push(self.data[i] + _rhs.data[i]);
                                    ^~~~~~~~~~~~
<anon>:23:42: 23:54 error: cannot move out of indexed content
<anon>:23             res.data.push(self.data[i] + _rhs.data[i]);
                                                   ^~~~~~~~~~~~

Add / the +运算符获取其参数的所有权,并且无​​法通过直接索引将所有权移出向量(通常,编译器无法告诉您以后不会再次尝试访问移出的索引,这将是一个安全问题)。 幸运的是,有一个解决方案:向量支持移出迭代器,并且可以遍历self_rhs以锁定步骤移出:

for (a, b) in self.data.into_iter().zip(_rhs.data.into_iter()) {
    res.data.push(a + b)
}

ab变量均为T类型,即所有权已转移。


小贴士,实际上可以使代码“迭代”更多:

fn add(self, _rhs: Matrix<T>) -> Matrix<T::Output>
{
    assert!(self.rows == _rhs.rows && self.cols == _rhs.cols,
            "attempting to add matrices of different sizes");

    let data = self.data.into_iter()
         .zip(_rhs.data.into_iter())
        .map(|(a,b)| a + b)
        .collect();
    Matrix {
        rows: self.rows,
        cols: self.cols,
        data: data
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM