在Rust中使用特征的泛型类型不匹配

ena*_*naJ 1 traits rust

我正在使用特征进行矩阵加法.我被通用类型不匹配所困扰.我的代码如下:

use std::{ops, fmt};

#[derive(PartialEq, Debug)]
pub struct Matrix<T> {
    data: Vec<T>,
    row: usize,
    col: usize,
}

impl<T: Copy> Matrix<T> {
    /// Creates a new matrix of `row` rows and `col` columns, and initializes
    /// the matrix with the elements in `values` in row-major order.
    pub fn new(row: usize, col: usize, values: &[T]) -> Matrix<T> {
        Matrix {
            data: values.to_vec(), // make copy and convert &[T] to vector type
            row: row,
            col: col,
        }
    }
}

impl<T: ops::Add<Output = T> + Copy> ops::Add for Matrix<T> {
    type Output = Self;

    /// Returns the sum of `self` and `rhs`. If `self.row != rhs.row || self.col != rhs.col`, panic.
    fn add(self, rhs: Self) -> Self::Output {

        assert!(self.col == rhs.col);
        assert!(self.row == rhs.row);

        let mut newdata = Vec::new(); // make a new vector to store result
        let mut sum: i32; // temp variable to record each addition

        for num1 in self.data.iter() {
            for num2 in rhs.data.iter() {
                sum = *num1 + *num2;
                newdata.push(sum)
            }
        }

        Matrix {
            data: newdata, // finally, return addition result using new_data
            row: self.row,
            col: self.col,
        }
    }
}

fn main() {
    let x = Matrix::new(2, 3, &[-6, -5, 0, 1, 2, 3]);
    let y = Matrix::new(2, 3, &[0, 1, 0, 0, 0, 0]);
    // z = x + y;
}
Run Code Online (Sandbox Code Playgroud)

编译程序,我得到两个关于类型不匹配的错误:

error[E0308]: mismatched types
  --> src/main.rs:36:23
   |
36 |                 sum = *num1 + *num2;
   |                       ^^^^^^^^^^^^^ expected i32, found type parameter
   |
   = note: expected type `i32`
   = note:    found type `T`

error[E0308]: mismatched types
  --> src/main.rs:41:9
   |
41 |         Matrix {
   |         ^ expected type parameter, found i32
   |
   = note: expected type `Matrix<T>`
   = note:    found type `Matrix<i32>`
Run Code Online (Sandbox Code Playgroud)

我的想法:

  1. num1 会解析向量并得到一个整数类型,这就是我用和来记录结果的原因.
  2. 我试图Matrix在函数的末尾返回一个类型值.

出了什么问题?

She*_*ter 6

这是代码可以依赖于方法的类型的完整知识:

impl<T: ops::Add<Output = T> + Copy> ops::Add for Matrix<T> {
    type Output = Self;
    fn add(self, rhs: Self) -> Self::Output {
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

基于此,如何做出这个假设?

num1将deref矢量并获得整数类型

没有办法知道具体类型T将是!

除此之外,即使它是某种整数类型,怎么可能假设求和i32是否可以接受?如果T是一个i64

解决方案是删除任何假设并让编译器完成其工作.从中删除类型注释sum并编译代码.我发现总是允许编译器在可能的情况下推断我的类型是一个好习惯.

也可以看看: