[英]How can I return a generic type from a member function in Rust
I'm trying to write a generic matrix class in Rust.我正在尝试在 Rust 中编写一个通用矩阵 class。 I'd like to have a
get
member function that returns a copy of the element at a given index in the matrix.我想要一个
get
成员 function ,它返回矩阵中给定索引处的元素副本。 The code currently looks like this:目前的代码如下所示:
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;
}
}
}
I get the following error from the Rust compiler (version 1.39.0):我从 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`
I'm struggling to understand what this error means.我很难理解这个错误的含义。 Is there some additional trait I need to use to constrain the
T
type?我需要使用一些额外的特征来约束
T
类型吗?
In eq
, self
is a Matrix<T> where T: PartialEq
as that's the bound for the impl
where eq
is defined.在
eq
中, self
是一个Matrix<T> where T: PartialEq
因为这是定义eq
的impl
的界限。 Calling get
on it requires it's a Matrix<T> where T: Copy
as that's the bound on the impl
where get
is defined.调用
get
需要它是一个Matrix<T> where T: Copy
因为这是定义get
的impl
的边界。 This is what the error message means:这就是错误消息的含义:
the method
get
exists but the following trait bounds were not satisfied:T: std::marker::Copy
方法
get
存在但不满足以下特征边界:T: std::marker::Copy
A type bound on one impl doesn't automatically get carried on to other impls.绑定在一个 impl 上的类型不会自动传递到其他 impl。
You could fix this with你可以用
impl<T> PartialEq for Matrix<T>
where
T: PartialEq + Copy
Or if you don't want to require this, you could return an &T
from get
and drop the where T: Copy
或者,如果您不想这样做,您可以从
get
返回&T
并删除where T: Copy
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.