]>
Commit | Line | Data |
---|---|---|
2c00a5a8 XL |
1 | # Operator Overloading |
2 | ||
3 | In Rust, many of the operators can be overloaded via traits. That is, some operators can | |
4 | be used to accomplish different tasks based on their input arguments. This is possible | |
5 | because operators are syntactic sugar for method calls. For example, the `+` operator in | |
6 | `a + b` calls the `add` method (as in `a.add(b)`). This `add` method is part of the `Add` | |
7 | trait. Hence, the `+` operator can be used by any implementor of the `Add` trait. | |
8 | ||
83c7162d | 9 | A list of the traits, such as `Add`, that overload operators can be found in [`core::ops`][ops]. |
2c00a5a8 XL |
10 | |
11 | ```rust,editable | |
12 | use std::ops; | |
13 | ||
14 | struct Foo; | |
15 | struct Bar; | |
16 | ||
17 | #[derive(Debug)] | |
18 | struct FooBar; | |
19 | ||
20 | #[derive(Debug)] | |
21 | struct BarFoo; | |
22 | ||
23 | // The `std::ops::Add` trait is used to specify the functionality of `+`. | |
24 | // Here, we make `Add<Bar>` - the trait for addition with a RHS of type `Bar`. | |
25 | // The following block implements the operation: Foo + Bar = FooBar | |
26 | impl ops::Add<Bar> for Foo { | |
27 | type Output = FooBar; | |
28 | ||
29 | fn add(self, _rhs: Bar) -> FooBar { | |
30 | println!("> Foo.add(Bar) was called"); | |
31 | ||
32 | FooBar | |
33 | } | |
34 | } | |
35 | ||
36 | // By reversing the types, we end up implementing non-commutative addition. | |
37 | // Here, we make `Add<Foo>` - the trait for addition with a RHS of type `Foo`. | |
38 | // This block implements the operation: Bar + Foo = BarFoo | |
39 | impl ops::Add<Foo> for Bar { | |
40 | type Output = BarFoo; | |
41 | ||
42 | fn add(self, _rhs: Foo) -> BarFoo { | |
43 | println!("> Bar.add(Foo) was called"); | |
44 | ||
45 | BarFoo | |
46 | } | |
47 | } | |
48 | ||
49 | fn main() { | |
50 | println!("Foo + Bar = {:?}", Foo + Bar); | |
51 | println!("Bar + Foo = {:?}", Bar + Foo); | |
52 | } | |
53 | ``` | |
54 | ||
55 | ### See Also | |
56 | ||
57 | [Add][add], [Syntax Index][syntax] | |
58 | ||
59 | [add]: https://doc.rust-lang.org/core/ops/trait.Add.html | |
60 | [ops]: https://doc.rust-lang.org/core/ops/ | |
61 | [syntax]:https://doc.rust-lang.org/book/second-edition/appendix-02-operators.html |