]> git.proxmox.com Git - rustc.git/blame - src/doc/rust-by-example/src/trait/ops.md
New upstream version 1.27.1+dfsg1
[rustc.git] / src / doc / rust-by-example / src / trait / ops.md
CommitLineData
2c00a5a8
XL
1# Operator Overloading
2
3In Rust, many of the operators can be overloaded via traits. That is, some operators can
4be used to accomplish different tasks based on their input arguments. This is possible
5because 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`
7trait. Hence, the `+` operator can be used by any implementor of the `Add` trait.
8
83c7162d 9A list of the traits, such as `Add`, that overload operators can be found in [`core::ops`][ops].
2c00a5a8
XL
10
11```rust,editable
12use std::ops;
13
14struct Foo;
15struct Bar;
16
17#[derive(Debug)]
18struct FooBar;
19
20#[derive(Debug)]
21struct 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
26impl 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
39impl 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
49fn 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