| 1 | use std::ops::{Add, AddAssign, Mul}; |
| 2 | |
| 3 | #[macro_export] |
| 4 | macro_rules! point { |
| 5 | ( $x:expr, $y:expr ) => { Point2D { x:$x, y:$y } }; |
| 6 | } |
| 7 | |
| 8 | #[derive(Debug, Copy, Clone, PartialEq)] |
| 9 | pub struct Point2D<T> { |
| 10 | pub x: T, |
| 11 | pub y: T, |
| 12 | } |
| 13 | |
| 14 | impl Point2D<f64> { |
| 15 | pub fn length(self) -> f64 { |
| 16 | ((self.x * self.x) + (self.y * self.y)).sqrt() |
| 17 | } |
| 18 | } |
| 19 | |
| 20 | impl<T: Add<Output=T>> Add for Point2D<T> { |
| 21 | type Output = Point2D<T>; |
| 22 | |
| 23 | fn add(self, rhs: Point2D<T>) -> Self::Output { |
| 24 | Point2D { x: self.x + rhs.x, y: self.y + rhs.y } |
| 25 | } |
| 26 | } |
| 27 | |
| 28 | impl<T: AddAssign> AddAssign for Point2D<T> { |
| 29 | fn add_assign(&mut self, rhs: Point2D<T>) { |
| 30 | self.x += rhs.x; |
| 31 | self.y += rhs.y; |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | #[derive(Default)] |
| 36 | pub struct Rect<T> { |
| 37 | pub width: T, |
| 38 | pub height: T, |
| 39 | } |
| 40 | |
| 41 | impl<T: Mul<Output=T> + Copy> Rect<T> { |
| 42 | #[allow(dead_code)] |
| 43 | pub fn area(&self) -> T { |
| 44 | self.width * self.height |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | impl<T> From<(T, T)> for Rect<T> { |
| 49 | fn from(item: (T, T)) -> Self { |
| 50 | Rect { width: item.0, height: item.1 } |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | #[cfg(test)] |
| 55 | mod tests { |
| 56 | use super::*; |
| 57 | |
| 58 | #[test] |
| 59 | fn immutable_copy_of_point() { |
| 60 | let a = point!(0, 0); |
| 61 | let mut b = a; // Copy |
| 62 | assert_eq!(a, b); // PartialEq |
| 63 | b.x = 1; |
| 64 | assert_ne!(a, b); // PartialEq |
| 65 | } |
| 66 | |
| 67 | #[test] |
| 68 | fn add_points() { |
| 69 | let mut a = point!(1, 0); |
| 70 | assert_eq!(a + point!(2, 2), point!(3, 2)); // Add |
| 71 | a += point!(2, 2); // AddAssign |
| 72 | assert_eq!(a, point!(3, 2)); |
| 73 | } |
| 74 | |
| 75 | #[test] |
| 76 | fn area_for_rect_of_multipliable_type() { |
| 77 | let r: Rect<_> = (30, 20).into(); // the Into trait uses the From trait |
| 78 | assert_eq!(r.area(), 30 * 20); |
| 79 | // let a = Rect::from(("a".to_string(), "b".to_string())).area(); // this doesn't work, because area() is not implemented for String |
| 80 | } |
| 81 | } |