[英]How can I return a generic type from a member function in Rust
我正在嘗試在 Rust 中編寫一個通用矩陣 class。 我想要一個get
成員 function ,它返回矩陣中給定索引處的元素副本。 目前的代碼如下所示:
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
因為這是定義eq
的impl
的界限。 調用get
需要它是一個Matrix<T> where T: Copy
因為這是定義get
的impl
的邊界。 這就是錯誤消息的含義:
方法
get
存在但不滿足以下特征邊界:T: std::marker::Copy
綁定在一個 impl 上的類型不會自動傳遞到其他 impl。
你可以用
impl<T> PartialEq for Matrix<T>
where
T: PartialEq + Copy
或者,如果您不想這樣做,您可以從get
返回&T
並刪除where T: Copy
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.