Hello! I've been learning Rust over the past few weeks, and have been having an issue with generics and traits.
I've been creating a simple Vector crate that mimics OpenGL's Vec2. I also wanted to have variants for f32
, f64
, usize
, etc. To do this I split the functionality into a trait that can be implemented.
Unfortunately, I've been getting an error with my Vec2Traits.norm()
method. The only solution to this that I've figured out is removing the method entirely. Here is my code (simplified into one file):
(Also I'm using the num_traits crate.)
use num_traits::{Num, real::Real};
trait Vec2Traits<T: Num + Real> {
fn new(x: T, y: T) -> Self;
// So default trait methods can access x and y
fn x(&self) -> T;
fn y(&self) -> T;
fn mag(&self) -> T {
self.mag2().sqrt()
}
fn mag2(&self) -> T {
self.x() * self.x() + self.y() * self.y()
}
fn norm(&self) -> Self
where
// Not sure if this is idiomic
Self: Sized,
{
// Main error here because {float} does not implement Div<T>
let r = 1.0 / self.mag();
Self::new(self.x() * r, self.y() * r)
}
}
#[derive(Debug)]
struct Vec2 {
pub x: f32,
pub y: f32
}
impl Vec2Traits<f32> for Vec2 {
fn new(x: f32, y: f32) -> Self {
Vec2 {x, y}
}
fn x(&self) -> f32 {
self.x
}
fn y(&self) -> f32 {
self.y
}
}
fn main() {
let v = Vec2::new(1.0, 5.0);
}
The error I'm getting is the following:
error[E0277]: cannot divide `{float}` by `T`
--> examples/vecslol.rs:22:21
|
22 | let r = 1.0 / self.mag();
| ^ no implementation for `{float} / T`
|
= help: the trait `Div<T>` is not implemented for `{float}`
For more information about this error, try `rustc --explain E0277`.
error: could not compile `manyvecs` due to previous error
exit status 101
Thank you for helping out! This is my first post, so I'm sorry if it's a little scuffed.