我正在 Rust 中创建一个简单的矩阵结构,并尝试实现一些基本的运算符方法:
use std::ops::Mul;
struct Matrix {
cols: i32,
rows: i32,
data: Vec<f32>,
}
impl Matrix {
fn new(cols: i32, rows: i32, data: Vec<f32>) -> Matrix {
Matrix {
cols: cols,
rows: rows,
data: data,
}
}
}
impl Mul<f32> for Matrix {
type Output = Matrix;
fn mul(&self, m: f32) -> Matrix {
let mut new_data = Vec::with_capacity(self.cols * self.rows);
for i in 0..self.cols * self.rows {
new_data[i] = self.data[i] * m;
}
return Matrix {
cols: *self.cols,
rows: *self.rows,
data: new_data,
};
}
}
fn main() {}
我仍在熟悉 Rust 和系统编程,我确信错误非常明显。编译器告诉我:
error[E0053]: method `mul` has an incompatible type for trait
--> src/main.rs:22:5
|
22 | fn mul(&self, m: f32) -> Matrix {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected struct `Matrix`, found &Matrix
|
= note: expected type `fn(Matrix, f32) -> Matrix`
found type `fn(&Matrix, f32) -> Matrix`
它指的是 for 循环的内容(我相信)。我尝试过尝试其他一些东西,但我无法理解它。
最佳答案
错误消息在这里:
error[E0053]: method `mul` has an incompatible type for trait
--> src/main.rs:22:5
|
22 | fn mul(&self, m: f32) -> Matrix {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected struct `Matrix`, found &Matrix
|
= note: expected type `fn(Matrix, f32) -> Matrix`
found type `fn(&Matrix, f32) -> Matrix`
让我们看看 Mul
特征来查看为什么您的实现不匹配:
pub trait Mul<RHS = Self> {
type Output;
fn mul(self, rhs: RHS) -> Self::Output;
}
这表示,除非您进一步指定任何内容,否则 RHS
将与 Self
具有相同的类型。 Self
是要实现该特征的类型。让我们看看您的定义:
impl Mul<f32> for Matrix {
type Output = Matrix;
fn mul(&self, m: f32) -> Matrix {}
}
就您而言,您已将 RHS
替换为 f32
,将 Output
替换为 Matrix
。另外,Matrix
是实现类型。让我们采用特征定义并代入,产生一些伪 Rust:
pub trait Mul {
fn mul(self, rhs: f32) -> Matrix;
}
现在你看出什么不同了吗?
// Trait
fn mul(self, m: f32) -> Matrix;
// Your implementation
fn mul(&self, m: f32) -> Matrix;
您错误地指定采用 &self
而不是 self
。
为了完整起见,这里是实现。我免费提供了样式修复!
impl Mul<f32> for Matrix {
type Output = Matrix;
fn mul(self, m: f32) -> Matrix {
let new_data = self.data.into_iter().map(|v| v * m).collect();
Matrix {
cols: self.cols,
rows: self.rows,
data: new_data,
}
}
}
这有点低效,因为它会释放和重新分配data
向量。由于您按值获取矩阵
,因此我们可以就地编辑它:
impl Mul<f32> for Matrix {
type Output = Matrix;
fn mul(mut self, m: f32) -> Matrix {
for v in &mut self.data {
*v *= m
}
self
}
}
关于struct - 方法 `mul` 的特征类型不兼容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33765397/