I have a Vec3<T>
structure, how can I implement the following method?
impl<T: num::Num + num::Float> Not<Vec3<T>> for Vec3<T> { fn not(&self) -> Vec3<T> { *self * (1.0 / (*self % *self).sqrt()) } }
error: inappropriate types: expected _
, found T
(expected floating point variable, type parameter found)
Type 1.0
is _
, and type (*self % *self).sqrt()
is T
And, it seems he cannot divide a by T.
I tried a different cast for 1.0:
*self * ((1.0 as T) / (*self % *self).sqrt())
error: non-scalar cast: _
like T
*self * (1.0.div((*self % *self).sqrt()))
error: inconsistent types: expected &_
, found T
(expected & -ptr, found type parameter)
What is the best way to implement this method?
Edit 1: As requested, here is my complete code:
use std::num::Float; pub struct Vec3<T> { pub x: T, pub y: T, pub z: T, } impl<T> Vec3<T> { pub fn new(x: T, y: T, z: T) -> Vec3<T> { Vec3 { x: x, y: y, z: z } } } impl<T: Float> Add<T, Vec3<T>> for Vec3<T> { fn add(&self, rhs: &T) -> Vec3<T> { Vec3 { x: self.x + *rhs, y: self.y + *rhs, z: self.z + *rhs } } } impl<T: Float> Add<Vec3<T>, Vec3<T>> for Vec3<T> { fn add(&self, rhs: &Vec3<T>) -> Vec3<T> { Vec3 { x: self.x + rhs.x, y: self.y + rhs.y, z: self.z + rhs.z } } } impl<T: Float> Mul<T, Vec3<T>> for Vec3<T> { fn mul(&self, rhs: &T) -> Vec3<T> { Vec3 { x: self.x * *rhs, y: self.y * *rhs, z: self.z * *rhs } } }
I would use Num
instead of Float
to have integer vectors, but since it is deprecated, I think the best option is to use a macro to duplicate code for all types. Here I duplicated Not
for f32
and f64