2016-11-04 64 views
1

我正在使用特徵做矩陣加法。我被通用類型不匹配卡住了。我的代碼如下:在鏽跡中使用特徵的泛型類型不匹配

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; 
} 

編譯程序,我得到了類型不匹配的兩個錯誤:

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>` 

我的想法:

  1. num1將DEREF載體,並得到一個整數類型,這就是爲什麼我使用總和來記錄結果。
  2. 我想在函數結尾返回一個Matrix類型的值。

怎麼回事?

回答

5

這是你的類型的整個知識的代碼可以依靠方法內部:在此基礎上

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

,它是如何將有可能做這樣的假設?

num1將DEREF載體和得到一個整數類型

沒有辦法知道什麼具體類型T會!

除此之外,即使它是一些整數類型,如何可以假設求和爲i32是可以接受的?如果Ti64怎麼辦?

解決方案是刪除任何假設並讓編譯器完成工作。從sum中刪除類型註釋並編譯代碼。我發現總是允許編譯器在可能的情況下推斷我的類型。

參見: