Guest User

Untitled

a guest
Jun 19th, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.96 KB | None | 0 0
  1. use std::ops;
  2.  
  3. struct Foo;
  4. struct Bar;
  5.  
  6. #[derive(Debug)]
  7. struct FooBar;
  8.  
  9. #[derive(Debug)]
  10. struct BarFoo;
  11.  
  12. // The `std::ops::Add` trait is used to specify the functionality of `+`.
  13. // Here, we make `Add<Bar>` - the trait for addition with a RHS of type `Bar`.
  14. // The following block implements the operation: Foo + Bar = FooBar
  15. impl ops::Add<Bar> for Foo {
  16. type Output = FooBar;
  17.  
  18. fn add(self, _rhs: Bar) -> FooBar {
  19. println!("> Foo.add(Bar) was called");
  20.  
  21. FooBar
  22. }
  23. }
  24.  
  25. // By reversing the types, we end up implementing non-commutative addition.
  26. // Here, we make `Add<Foo>` - the trait for addition with a RHS of type `Foo`.
  27. // This block implements the operation: Bar + Foo = BarFoo
  28. impl ops::Add<Foo> for Bar {
  29. type Output = BarFoo;
  30.  
  31. fn add(self, _rhs: Foo) -> BarFoo {
  32. println!("> Bar.add(Foo) was called");
  33.  
  34. BarFoo
  35. }
  36. }
  37.  
  38. fn main() {
  39. println!("Foo + Bar = {:?}", Foo + Bar);
  40. println!("Bar + Foo = {:?}", Bar + Foo);
  41. }
Add Comment
Please, Sign In to add comment