mathmatics.rs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. use point::Point;
  2. fn main() {
  3. // Defining 2 Points
  4. let p: Point<i32> = Point::from((3_i32, 2));
  5. let p1: Point<i32> = Point::from((1_i32, 2));
  6. // ^
  7. // Both are i32
  8. // Use a number to add to both x and y
  9. let p2 = p.clone() + 1;
  10. // ^
  11. // Clone is needed because + operator takes ownership
  12. // (So we'd lose access to p)
  13. assert_eq!(p2.x, 4, "p2.x = {} (expected 4)", p2.x);
  14. assert_eq!(p2.y, 3, "p2.y = {} (expected 3)", p2.y);
  15. // Or use a tuple of 2 numbers to add to x and y respectively
  16. let p3 = p1.clone() + (1, 2);
  17. assert_eq!(p3.x, 2, "p3.x = {} (expected 2)", p3.x);
  18. assert_eq!(p3.y, 4, "p3.y = {} (expected 4)", p3.y);
  19. // Let's clone p so we can manipulate it directly
  20. let mut p4 = p.clone();
  21. p4 += 2; // Change p4 directly (Clone it if you don't want to modify it directly)
  22. assert_eq!(p4.x, 5, "p4.x = {} (expected 5)", p4.x);
  23. assert_eq!(p4.y, 4, "p4.y = {} (expected 4)", p4.y);
  24. let mut p4 = p1.clone();
  25. p4 += (-1, 0); // Because it's i32, we can use negative to subtract (or just use -= operator)
  26. assert_eq!(p4.x, 0, "p4.x = {} (expected 0)", p4.x);
  27. assert_eq!(p4.y, 2, "p4.y = {} (expected 2)", p4.y);
  28. // Operators that return a new Point
  29. // Add +
  30. // Sub -
  31. // Mul *
  32. // Div /
  33. // Rem %
  34. // Operators that modify their Point (modifies self)
  35. // AddAssign +=
  36. // SubAssign -=
  37. // MulAssign *=
  38. // DivAssign /=
  39. // RemAssign %=
  40. }