【发布时间】:2019-11-17 18:51:26
【问题描述】:
我正在尝试用 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 类型吗?
【问题讨论】:
标签: rust