I am trying to implement a Vector
struct. It is declared as follows:
use num_traits::Float;
pub struct Vec3<T> {
pub x: T,
pub y: T,
pub z: T,
}
impl<T> Vec3<T>
where
T: Float,
{
pub fn new(x: T, y: T, z: T) -> Vec3<T> {
Vec3 { x, y, z }
}
}
I would like to have the ability to add an instance of this struct to a generic float value. I think in my case I would be anything that implements the Float
trait:
let vec = Vec3::new(1.0, 1.0, 1.0);
let res = 1.0 + vec; // this should work for both f32 and f64
I was going to just implement the Add
trait for Float
, so I wrote:
use std::ops::Add;
impl<T: Float> Add<Vec3<T>> for T {
type Output = Vec3<T>;
fn add(self, other: Vec3<T>) -> Vec3<T> {
Vec3::new(self + other.x, self + other.y, self + other.z)
}
}
Which gives me the following error:
error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g. `MyStruct<T>`)
--> src/lib.rs:20:1
|
20 | impl<T: Float> Add<Vec3<T>> for T {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type parameter `T` must be used as the type parameter for some local type
|
= note: only traits defined in the current crate can be implemented for a type parameter
The closest related solution I could find online is the same that error message suggest: to wrap the Float
trait with a struct, which does not fit with my requirements. I also tried to declare a local trait that contains Float
, but that didn't really help.