1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
use std::ops::Add; use std::ops::AddAssign; use std::ops::Sub; use std::ops::Neg; use num_traits::{Float, ToPrimitive}; #[derive(Clone, Copy, Debug, PartialEq)] pub struct Point<T: Float> { pub x: T, pub y: T, } impl<T> Point<T> where T: Float + ToPrimitive { pub fn new(x: T, y: T) -> Point<T> { Point {x: x, y: y} } } impl<T> Add for Point<T> where T: Float + ToPrimitive { type Output = Point<T>; fn add(self, rhs: Point<T>) -> Point<T> { Point::new(self.x + rhs.x, self.y + rhs.y) } } impl<T> Sub for Point<T> where T: Float + ToPrimitive{ type Output = Point<T>; fn sub(self, rhs: Point<T>) -> Point<T> { Point::new(self.x - rhs.x, self.y - rhs.y) } } impl<T> AddAssign for Point<T> where T: Float + ToPrimitive { fn add_assign(&mut self, rhs: Point<T>) { self.x = self.x + rhs.x; self.y = self.y + rhs.y; } } impl<T> Neg for Point<T> where T: Float + ToPrimitive { type Output = Point<T>; fn neg(self) -> Point<T> { Point::new(-self.x, -self.y) } } #[cfg(test)] mod test { use ::point::Point; #[test] fn point_test() { let p1 = Point::new(12.0, 33.3); let p2 = Point{x: 12.0, y: 33.3}; assert_eq!(p1, p2); assert_eq!(p1.x, p2.x); assert_eq!(p1.y, p2.y); } }