我正在用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() {}我仍在熟悉锈蚀和系统编程,我确信错误是相当明显的。编译器告诉我:
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循环的内容(我相信)。我试过玩一些其他的东西,但我无法理解它。
发布于 2015-11-17 19:38:50
错误信息在这里是即席的:
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 {}
}在您的例子中,f32代替了RHS,Matrix代替了Output。另外,Matrix是实现类型。让我们用特征定义来代替,产生一些伪锈:
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向量时有点低效。由于您使用的是Matrix值,所以我们只需在适当的位置编辑它:
impl Mul<f32> for Matrix {
type Output = Matrix;
fn mul(mut self, m: f32) -> Matrix {
for v in &mut self.data {
*v *= m
}
self
}
}https://stackoverflow.com/questions/33765397
复制相似问题