Consider the following vector struct:
struct Vec3([f64; 3]);
I'd like to be able to use the +
operator when dealing with these vectors. So I started off with:
impl Add for Vec3 {
type Output = Vec3;
fn add(self, other: Vec3) -> Vec3 {
Vec3::new_with(self[0] + other[0], self[1] + other[1], self[2] + other[2])
}
}
Which works fine, until the point that I don't want these structs to be moved, we can work with their references instead, so I end up doing 3 more impls:
impl Add for &Vec3 {
type Output = Vec3;
fn add(self, other: &Vec3) -> Vec3 {
Vec3::new_with(self[0] + other[0], self[1] + other[1], self[2] + other[2])
}
}
impl Add<Vec3> for &Vec3 {
type Output = Vec3;
fn add(self, other: Vec3) -> Vec3 {
Vec3::new_with(self[0] + other[0], self[1] + other[1], self[2] + other[2])
}
}
impl Add<&Vec3> for Vec3 {
type Output = Vec3;
fn add(self, other: &Vec3) -> Vec3 {
Vec3::new_with(self[0] + other[0], self[1] + other[1], self[2] + other[2])
}
}
All of these add
methods have exactly the same implementation. Is there a simpler way to do this?