Created
March 2, 2018 16:30
-
-
Save eisterman/89fd9985cd6a634b0cf063de080bdd1c to your computer and use it in GitHub Desktop.
Vector2 by eisterman
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extern crate num; | |
use num::Float; | |
use std::ops::{Add,Sub,Mul}; | |
#[derive(Debug, Eq, PartialEq)] | |
struct Vector2<T> { | |
x: T, | |
y: T, | |
} | |
impl<T: Add<Output=T>> Add for Vector2<T> { | |
type Output = Vector2<T>; | |
fn add(self, other: Vector2<T>) -> Vector2<T> { | |
Vector2::<T> { x: self.x + other.x, y: self.y + other.y } | |
} | |
} | |
impl<T: Sub<Output=T>> Sub for Vector2<T> { | |
type Output = Vector2<T>; | |
fn sub(self, other: Vector2<T>) -> Vector2<T> { | |
Vector2::<T> { x: self.x - other.x, y: self.y - other.y } | |
} | |
} | |
impl<T> Mul<T> for Vector2<T> where T: Mul<Output=T> + Copy { | |
type Output = Vector2<T>; | |
fn mul(self, rhs: T) -> Vector2<T> { | |
Vector2::<T> { x: self.x * rhs, y: self.y * rhs } | |
} | |
} | |
impl<T> Vector2<T> where T: Float { | |
fn norm(self) -> T { | |
(self.x * self.x + self.y * self.y).sqrt() | |
} | |
} | |
//TODO: Come fare il 5 * Vec ? | |
#[test] | |
fn add_trait() { | |
assert_eq!(Vector2::<f64> { x: 4., y: 1.}, Vector2::<f64> {x:3., y:1.5} + Vector2::<f64> {x:1., y:-0.5} ); | |
} | |
#[test] | |
fn sub_trait() { | |
assert_eq!(Vector2::<f64> { x: 2., y: 2.}, Vector2::<f64> {x:3., y:1.5} - Vector2::<f64> {x:1., y:-0.5} ); | |
} | |
#[test] | |
fn mul_trait() { | |
assert_eq!(Vector2::<f64> { x: 6., y: 3.}, Vector2::<f64> {x:3., y:1.5} * 2. ); | |
} | |
#[test] | |
fn norm_test() { | |
assert_eq!(Vector2::<f64> { x: 4., y: -3.}.norm(), 5_f64); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment