我想在 rust`e 中编写一些代码,但遇到了一些困难。我用三个相同类型的字段创建了一个结构向量,为此我需要重载加法、减法和乘法运算符。尽管我根据书籍和互联网上的示例做了所有事情,但尝试重载加法运算符失败了。这是代码本身:
use std::ops::Add;
struct Vector<T> {
x1: T,
x2: T,
x3: T,
}
impl<T> Add<T> for Vector<T>
{
type Output = Vector<T>;
fn add(self, rhs: Vector<T>) -> Vector<T> {
Vector {x1: self.x1 + rhs.x1, x2: self.x2 + rhs.x2, x3: self.x3 + rhs.x3};
}
}
fn main() {
let vector1 = Vector { x1: 5.6, x2: 7.2, x3: 2.5 };
let vector2 = Vector { x1: -0.1, x2: 10.9, x3: 3.3 };
println!("Вектор 1: ({}, {}, {})", vector1.x1, vector1.x2, vector1.x3);
println!("Вектор 2: ({}, {}, {})", vector2.x1, vector2.x2, vector2.x3);
let vector3 = vector1 + vector2;
println!("Сумма векторов: ({}, {}, {})", vector3.x1, vector3.x2, vector3.x3);
}
错误:
error[E0053]: method `add` has an incompatible type for trait
--> main.rs:13:5
|
13 | / fn add(self, rhs: Vector<T>) -> Vector<T> {
14 | | Vector {x1: self.x1 + rhs.x1, x2: self.x2 + rhs.x2, x3: self.x3 + rhs.x3};
15 | | }
| |_____^ expected type parameter, found struct `Vector`
|
= note: expected type `fn(Vector<T>, T) -> Vector<T>`
found type `fn(Vector<T>, Vector<T>) -> Vector<T>`
error: aborting due to previous error(s)
在在线编译器中编写和编译。提前致谢。