【发布时间】:2015-12-02 12:52:49
【问题描述】:
我正在实现一个快速几何板条箱进行练习,我想实现两个结构,Vector 和 Normal(这是因为标准向量和法线向量通过某些变换以不同方式映射)。我已经实现了以下特征:
trait Components {
fn new(x: f32, y: f32, z: f32) -> Self;
fn x(&self) -> f32;
fn y(&self) -> f32;
fn z(&self) -> f32;
}
我还想将两个向量以及两个法线加在一起,所以我的块看起来像这样:
impl Add<Vector> for Vector {
type Output = Vector;
fn add(self, rhs: Vector) -> Vector {
Vector { vals: [
self.x() + rhs.x(),
self.y() + rhs.y(),
self.z() + rhs.z()] }
}
}
对于Normals,几乎完全相同的impl。我真正想要的是为每个实现Components 的结构提供默认的Add impl,因为通常它们都会以相同的方式添加(例如,名为Point 的第三个结构会做同样的事情)。除了为Point、Vector 和Normal 写出三个相同的实现之外,还有其他方法吗?可能看起来像这样:
impl Add<Components> for Components {
type Output = Components;
fn add(self, rhs: Components) -> Components {
Components::new(
self.x() + rhs.x(),
self.y() + rhs.y(),
self.z() + rhs.z())
}
}
“Components”会自动替换为适当的类型。我想我可以在宏中做到这一点,但这对我来说似乎有点 hacky。
【问题讨论】:
标签: rust