我正在尝试在Rust中编写一个通用矩阵类。我想要一个get
成员函数,该函数在矩阵的给定索引处返回元素的副本。当前代码如下:
mod math {
pub struct Matrix<T> {
rows: usize,
columns: usize,
data: Vec<T>,
}
impl<T> Matrix<T> where T: Copy {
pub fn empty(rows: usize, columns: usize) -> Matrix<T> {
return Matrix {
rows: rows,
columns: columns,
data: Vec::with_capacity(rows * columns),
};
}
pub fn get(&self, row: usize, column: usize) -> T {
return self.data[column + row * self.columns];
}
}
impl<T> PartialEq for Matrix<T>
where
T: PartialEq,
{
fn eq(&self, other: &Self) -> bool {
if self.rows != other.rows || self.columns != other.columns {
return true;
}
for i in 0..self.rows {
for j in 0..self.columns {
if self.get(i, j) != other.get(i, j) {
return false;
}
}
}
return true;
}
}
}
我从Rust编译器(1.39.0版中得到以下错误:
error[E0599]: no method named `get` found for type `&math::Matrix<T>` in the current scope
--> <source>:33:29
|
33 | if self.get(i, j) != other.get(i, j) {
| ^^^ method not found in `&math::Matrix<T>`
|
= note: the method `get` exists but the following trait bounds were not satisfied:
`T : std::marker::Copy`
= help: items from traits can only be used if the trait is implemented and in scope
= note: the following traits define an item `get`, perhaps you need to implement one of them:
candidate #1: `core::panic::BoxMeUp`
candidate #2: `std::slice::SliceIndex`
我正在努力了解此错误的含义。我需要使用一些其他特征来约束T
类型吗?
在eq
中,self
是Matrix<T> where T: PartialEq
,但是get
要求self
是Matrix<T> where T: Copy
。
您可以通过以下方法解决此问题
impl<T> PartialEq for Matrix<T>
where
T: PartialEq + Copy
绑定在一个impl上的类型不会自动继承到其他impl。