I am introducing a box with fast geometry for practice, and I want to implement two Vector and Normal structures (this is due to the fact that standard vectors and normal vectors display differently through certain transformations). I implemented the following symptom:
trait Components { fn new(x: f32, y: f32, z: f32) -> Self; fn x(&self) -> f32; fn y(&self) -> f32; fn z(&self) -> f32; }
I would also like to add two vectors together, as well as two normals, so I have blocks that look like this:
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()] } } }
And almost the same impl for Normal s. I really want to provide a default Add impl for each structure that implements Components , since they will usually all add the same path (for example, a third structure called Point will do the same). Is there a way to do this, besides writing three identical implementations for Point , Vector and Normal ? Something that might look like this:
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()) } }
Where " Components " is automatically replaced by the corresponding type. I suppose I could do it in a macro, but it seems a bit hacked to me.
source share