Advertisement
Guest User

Untitled

a guest
Oct 13th, 2019
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.83 KB | None | 0 0
  1. use std::ops::*;
  2.  
  3. macro_rules! impl_op {
  4. (impl $trait:ident for $type:ident {
  5. fn $fn:ident;
  6. }) => {
  7. impl $trait for $type {
  8. type Output = $type;
  9. fn $fn(self, other: $type) -> $type {
  10. $type((self.0).$fn(other.0))
  11. }
  12. }
  13. }
  14. }
  15.  
  16. macro_rules! impl_op_assign {
  17. (impl $trait:ident for $type:ident {
  18. fn $fn:ident;
  19. }) => {
  20. impl $trait for $type {
  21. fn $fn(&mut self, other: $type) {
  22. (self.0).$fn(other.0)
  23. }
  24. }
  25. }
  26. }
  27.  
  28. #[derive(Debug, Copy, Clone)]
  29. struct X(i32);
  30.  
  31. impl_op! {
  32. impl Add for X {
  33. fn add;
  34. }
  35. }
  36.  
  37. impl_op_assign! {
  38. impl AddAssign for X {
  39. fn add_assign;
  40. }
  41. }
  42.  
  43. fn main() {
  44. let mut x1 = X(10);
  45. let x2 = X(5);
  46. dbg!(x1 + x2);
  47. x1 += x2;
  48. dbg!(x1);
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement