1 // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Overloadable operators.
13 //! Implementing these traits allows you to overload certain operators.
15 //! Some of these traits are imported by the prelude, so they are available in
16 //! every Rust program. Only operators backed by traits can be overloaded. For
17 //! example, the addition operator (`+`) can be overloaded through the [`Add`]
18 //! trait, but since the assignment operator (`=`) has no backing trait, there
19 //! is no way of overloading its semantics. Additionally, this module does not
20 //! provide any mechanism to create new operators. If traitless overloading or
21 //! custom operators are required, you should look toward macros or compiler
22 //! plugins to extend Rust's syntax.
24 //! Implementations of operator traits should be unsurprising in their
25 //! respective contexts, keeping in mind their usual meanings and
26 //! [operator precedence]. For example, when implementing [`Mul`], the operation
27 //! should have some resemblance to multiplication (and share expected
28 //! properties like associativity).
30 //! Note that the `&&` and `||` operators short-circuit, i.e. they only
31 //! evaluate their second operand if it contributes to the result. Since this
32 //! behavior is not enforceable by traits, `&&` and `||` are not supported as
33 //! overloadable operators.
35 //! Many of the operators take their operands by value. In non-generic
36 //! contexts involving built-in types, this is usually not a problem.
37 //! However, using these operators in generic code, requires some
38 //! attention if values have to be reused as opposed to letting the operators
39 //! consume them. One option is to occasionally use [`clone`].
40 //! Another option is to rely on the types involved providing additional
41 //! operator implementations for references. For example, for a user-defined
42 //! type `T` which is supposed to support addition, it is probably a good
43 //! idea to have both `T` and `&T` implement the traits [`Add<T>`][`Add`] and
44 //! [`Add<&T>`][`Add`] so that generic code can be written without unnecessary
49 //! This example creates a `Point` struct that implements [`Add`] and [`Sub`],
50 //! and then demonstrates adding and subtracting two `Point`s.
53 //! use std::ops::{Add, Sub};
55 //! #[derive(Debug, PartialEq)]
61 //! impl Add for Point {
62 //! type Output = Point;
64 //! fn add(self, other: Point) -> Point {
65 //! Point {x: self.x + other.x, y: self.y + other.y}
69 //! impl Sub for Point {
70 //! type Output = Point;
72 //! fn sub(self, other: Point) -> Point {
73 //! Point {x: self.x - other.x, y: self.y - other.y}
77 //! assert_eq!(Point {x: 3, y: 3}, Point {x: 1, y: 0} + Point {x: 2, y: 3});
78 //! assert_eq!(Point {x: -1, y: -3}, Point {x: 1, y: 0} - Point {x: 2, y: 3});
81 //! See the documentation for each trait for an example implementation.
83 //! The [`Fn`], [`FnMut`], and [`FnOnce`] traits are implemented by types that can be
84 //! invoked like functions. Note that [`Fn`] takes `&self`, [`FnMut`] takes `&mut
85 //! self` and [`FnOnce`] takes `self`. These correspond to the three kinds of
86 //! methods that can be invoked on an instance: call-by-reference,
87 //! call-by-mutable-reference, and call-by-value. The most common use of these
88 //! traits is to act as bounds to higher-level functions that take functions or
89 //! closures as arguments.
91 //! Taking a [`Fn`] as a parameter:
94 //! fn call_with_one<F>(func: F) -> usize
95 //! where F: Fn(usize) -> usize
100 //! let double = |x| x * 2;
101 //! assert_eq!(call_with_one(double), 2);
104 //! Taking a [`FnMut`] as a parameter:
107 //! fn do_twice<F>(mut func: F)
114 //! let mut x: usize = 1;
116 //! let add_two_to_x = || x += 2;
117 //! do_twice(add_two_to_x);
120 //! assert_eq!(x, 5);
123 //! Taking a [`FnOnce`] as a parameter:
126 //! fn consume_with_relish<F>(func: F)
127 //! where F: FnOnce() -> String
129 //! // `func` consumes its captured variables, so it cannot be run more
131 //! println!("Consumed: {}", func());
133 //! println!("Delicious!");
135 //! // Attempting to invoke `func()` again will throw a `use of moved
136 //! // value` error for `func`
139 //! let x = String::from("x");
140 //! let consume_and_return_x = move || x;
141 //! consume_with_relish(consume_and_return_x);
143 //! // `consume_and_return_x` can no longer be invoked at this point
146 //! [`Fn`]: trait.Fn.html
147 //! [`FnMut`]: trait.FnMut.html
148 //! [`FnOnce`]: trait.FnOnce.html
149 //! [`Add`]: trait.Add.html
150 //! [`Sub`]: trait.Sub.html
151 //! [`Mul`]: trait.Mul.html
152 //! [`clone`]: ../clone/trait.Clone.html#tymethod.clone
153 //! [operator precedence]: ../../reference/expressions.html#expression-precedence
155 #![stable(feature = "rust1", since = "1.0.0")]
168 #[stable(feature = "rust1", since = "1.0.0")]
169 pub use self::arith::{Add, Sub, Mul, Div, Rem, Neg};
170 #[stable(feature = "op_assign_traits", since = "1.8.0")]
171 pub use self::arith::{AddAssign, SubAssign, MulAssign, DivAssign, RemAssign};
173 #[stable(feature = "rust1", since = "1.0.0")]
174 pub use self::bit::{Not, BitAnd, BitOr, BitXor, Shl, Shr};
175 #[stable(feature = "op_assign_traits", since = "1.8.0")]
176 pub use self::bit::{BitAndAssign, BitOrAssign, BitXorAssign, ShlAssign, ShrAssign};
178 #[stable(feature = "rust1", since = "1.0.0")]
179 pub use self::deref::{Deref, DerefMut};
181 #[stable(feature = "rust1", since = "1.0.0")]
182 pub use self::drop::Drop;
184 #[stable(feature = "rust1", since = "1.0.0")]
185 pub use self::function::{Fn, FnMut, FnOnce};
187 #[stable(feature = "rust1", since = "1.0.0")]
188 pub use self::index::{Index, IndexMut};
190 #[stable(feature = "rust1", since = "1.0.0")]
191 pub use self::range::{Range, RangeFrom, RangeFull, RangeTo};
193 #[stable(feature = "inclusive_range", since = "1.26.0")]
194 pub use self::range::{RangeInclusive, RangeToInclusive, RangeBounds, Bound};
196 #[unstable(feature = "try_trait", issue = "42327")]
197 pub use self::try::Try;
199 #[unstable(feature = "generator_trait", issue = "43122")]
200 pub use self::generator::{Generator, GeneratorState};
202 #[unstable(feature = "coerce_unsized", issue = "27732")]
203 pub use self::unsize::CoerceUnsized;
205 #[unstable(feature = "dispatch_from_dyn", issue = "0")]
206 pub use self::unsize::DispatchFromDyn;