【发布时间】:2014-08-26 23:28:35
【问题描述】:
给定以下结构:
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 {
...
对于其他实现,反之亦然。
【问题讨论】:
-
@ChrisMorgan 这并不是真正的重复。这个问题有两个具体的
impls,而那个问题有一个通用的impl和一个具体的。