I'm trying to make a test with generics and traits and hit a wall. I want to add a FromPoint
method to my generic SphericalPoint<T>
type but I don't understand how to provide a generic number operations trait:
struct Point<T> {
x: T,
y: T,
}
trait FloatTrait {
fn my_cos(&self) -> Self;
fn my_sin(&self) -> Self;
fn my_sqrt(&self) -> Self;
fn my_atan2(&self, v: Self) -> Self;
}
struct SphericalPoint<T: FloatTrait> {
r: T,
theta: T,
}
impl<T: Copy + FloatTrait + std::ops::Add<Output = T> + std::ops::Mul<Output = T>>
SphericalPoint<T>
{
fn to_point(&self) -> Point<T> {
Point {
x: self.r * self.theta.my_cos(),
y: self.r * self.theta.my_sin(),
}
}
fn from_point(p: &Point<T>) -> SphericalPoint<T> {
SphericalPoint {
r: (p.x + p.y).my_sqrt(),
theta: p.y.my_atan2(p.x),
}
}
}
I tried to add a FloatTrait
that would make sure the types have the methods I need, but then it doesn't get fulfilled automatically, so I would need to implement it with alias names for each methods (like fn mysin(&self) -> Self;
, which is really silly).