【发布时间】:2015-04-29 11:48:29
【问题描述】:
为了学习 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 特征,但是在我尝试执行此操作的任何地方,我要么得到相同的错误,要么出现解析错误。
顺便说一下,我对矩阵的定义是
pub struct Matrix<T> {
pub rows: usize,
pub cols: usize,
pub data: Vec<T>,
}
【问题讨论】:
标签: rust