Operator Overloading

In Rust, many of the operators can be overloaded via traits. That is, some operators can be used to accomplish different tasks based on their input arguments. This is possible because operators are syntactic sugar for method calls. For example, the + operator in a + b calls the add method (as in a.add(b)). This add method is part of the Add trait. Hence, the + operator can be used by any implementor of the Add trait.

A list of the traits, such as Add, that overload operators can be found in core::ops.

1. use std::ops;

3. struct Foo;
4. struct Bar;

6. #[derive(Debug)]
7. struct FooBar;

9. #[derive(Debug)]
10. struct BarFoo;

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;

18. fn add(self, _rhs: Bar) -> FooBar {
19. println!("> Foo.add(Bar) was called");

21. FooBar
22. }
23. }

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;

31. fn add(self, _rhs: Foo) -> BarFoo {
32. println!("> Bar.add(Foo) was called");

34. BarFoo
35. }
36. }

38. fn main() {
39. println!("Foo + Bar = {:?}", Foo + Bar);
40. println!("Bar + Foo = {:?}", Bar + Foo);
41. }

See Also

Add, Syntax Index