I am implementing a quick geometry crate for practice, and I want to implement two structs, Vector
and Normal
(this is because standard vectors and normal vectors map through certain transformations differently). I've implemented the following trait:
trait Components {
fn new(x: f32, y: f32, z: f32) -> Self;
fn x(&self) -> f32;
fn y(&self) -> f32;
fn z(&self) -> f32;
}
I'd also like to be 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 exact same impl
for Normal
s. What I really want is to provide a default Add impl
for every struct that implements Components
, since typically, they all will add the same way (e.g. a third struct called Point
will do the same thing). Is there a way of doing this besides writing out 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
" would automatically get replaced by the appropriate type. I suppose I could do it in a macro, but that seems a little hacky to me.