给定以下结构体:
struct Vector3D {
x: f32,
y: f32,
z: f32
}
我希望重载*
操作符在右侧是一个Vector3D
时可以进行点积运算,在右侧是一个f32
时可以进行逐元素乘法。我的代码如下:
// Multiplication with scalar
impl Mul<f32, Vector3D> for Vector3D {
fn mul(&self, f: &f32) -> Vector3D {
Vector3D {x: self.x * *f, y: self.y * *f, z: self.z * *f}
}
}
// Multiplication with vector, aka dot product
impl Mul<Vector3D, f32> for Vector3D {
fn mul(&self, other: &Vector3D) -> f32 {
self.x * other.x + self.y * other.y + self.z * other.z
}
}
编译器针对第一个 impl 块发出如下提示:
Vector3D.rs:40:1: 44:2 error: conflicting implementations for trait `std::ops::Mul`
Vector3D.rs:40 impl Mul<f32, Vector3D> for Vector3D {
...
Vector3D.rs:53:1: 57:2 note: note conflicting implementation here
Vector3D.rs:53 impl Mul<Vector3D, f32> for Vector3D {
...
对于另一个实现,情况相反。
impl
,而那个问题有一个通用的impl
和一个具体的impl
。 - huon