My question is similar to the one addressed in this issue.
I'm trying to make a generic vector struct and I have the following working:
use std::ops::{Add, Sub};
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Vec2<T> where
T: Add<Output = T> + Sub<Output = T>
{
pub x: T,
pub y: T,
}
impl<T> Vec2<T> where
T: Add<Output = T> + Sub<Output = T>
{
pub fn new(x: T, y: T) -> Vec2<T> {
Vec2 { x, y }
}
}
// Overload `+` operator for Vec2
impl<T> Add for Vec2<T> where
T: Add<Output = T> + Sub<Output = T>
{
type Output = Self;
fn add(self, other: Self) -> Self::Output {
Self {
x: self.x + other.x,
y: self.y + other.y,
}
}
}
// Overload `-` operator for Vec2
impl<T> Sub for Vec2<T> where
T: Add<Output = T> + Sub<Output = T>
{
type Output = Self;
fn sub(self, other: Self) -> Self::Output {
Self {
x: self.x - other.x,
y: self.y - other.y,
}
}
}
But as you can see, this Add<Output = T> + Sub<Output = T> bound is a little messy, especially if I plan to implement more traits. Is there some way to use macros or type aliasing to so I can do something along the lines of:
trait Num: Add + Sub {}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Vec2<T> where
T: Num
{
...
}
// Overload `+` operator for Vec2
impl<T> Add for Vec2<T> where
T: Num
{
...
}
Note: Understandably, the code above produces a compilation error. If you look at the documentation for either the std::ops::Add or std::ops::Sub traits, they have a default generic type <Rhs = Self> whose size cannot be determined at compilation time, so I'm not sure if what I'm asking is even possible. But it would be nice if there was some workaround.