]> git.lizzy.rs Git - rust.git/blob - src/libcore/ops/mod.rs
Rollup merge of #55567 - durka:derive-debug-uninhabited, r=nikomatsakis
[rust.git] / src / libcore / ops / mod.rs
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.
4 //
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.
10
11 //! Overloadable operators.
12 //!
13 //! Implementing these traits allows you to overload certain operators.
14 //!
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.
23 //!
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).
29 //!
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.
34 //!
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
45 //! cloning.
46 //!
47 //! # Examples
48 //!
49 //! This example creates a `Point` struct that implements [`Add`] and [`Sub`],
50 //! and then demonstrates adding and subtracting two `Point`s.
51 //!
52 //! ```rust
53 //! use std::ops::{Add, Sub};
54 //!
55 //! #[derive(Debug, PartialEq)]
56 //! struct Point {
57 //!     x: i32,
58 //!     y: i32,
59 //! }
60 //!
61 //! impl Add for Point {
62 //!     type Output = Point;
63 //!
64 //!     fn add(self, other: Point) -> Point {
65 //!         Point {x: self.x + other.x, y: self.y + other.y}
66 //!     }
67 //! }
68 //!
69 //! impl Sub for Point {
70 //!     type Output = Point;
71 //!
72 //!     fn sub(self, other: Point) -> Point {
73 //!         Point {x: self.x - other.x, y: self.y - other.y}
74 //!     }
75 //! }
76 //!
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});
79 //! ```
80 //!
81 //! See the documentation for each trait for an example implementation.
82 //!
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.
90 //!
91 //! Taking a [`Fn`] as a parameter:
92 //!
93 //! ```rust
94 //! fn call_with_one<F>(func: F) -> usize
95 //!     where F: Fn(usize) -> usize
96 //! {
97 //!     func(1)
98 //! }
99 //!
100 //! let double = |x| x * 2;
101 //! assert_eq!(call_with_one(double), 2);
102 //! ```
103 //!
104 //! Taking a [`FnMut`] as a parameter:
105 //!
106 //! ```rust
107 //! fn do_twice<F>(mut func: F)
108 //!     where F: FnMut()
109 //! {
110 //!     func();
111 //!     func();
112 //! }
113 //!
114 //! let mut x: usize = 1;
115 //! {
116 //!     let add_two_to_x = || x += 2;
117 //!     do_twice(add_two_to_x);
118 //! }
119 //!
120 //! assert_eq!(x, 5);
121 //! ```
122 //!
123 //! Taking a [`FnOnce`] as a parameter:
124 //!
125 //! ```rust
126 //! fn consume_with_relish<F>(func: F)
127 //!     where F: FnOnce() -> String
128 //! {
129 //!     // `func` consumes its captured variables, so it cannot be run more
130 //!     // than once
131 //!     println!("Consumed: {}", func());
132 //!
133 //!     println!("Delicious!");
134 //!
135 //!     // Attempting to invoke `func()` again will throw a `use of moved
136 //!     // value` error for `func`
137 //! }
138 //!
139 //! let x = String::from("x");
140 //! let consume_and_return_x = move || x;
141 //! consume_with_relish(consume_and_return_x);
142 //!
143 //! // `consume_and_return_x` can no longer be invoked at this point
144 //! ```
145 //!
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
154
155 #![stable(feature = "rust1", since = "1.0.0")]
156
157 mod arith;
158 mod bit;
159 mod deref;
160 mod drop;
161 mod function;
162 mod generator;
163 mod index;
164 mod range;
165 mod try;
166 mod unsize;
167
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};
172
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};
177
178 #[stable(feature = "rust1", since = "1.0.0")]
179 pub use self::deref::{Deref, DerefMut};
180
181 #[stable(feature = "rust1", since = "1.0.0")]
182 pub use self::drop::Drop;
183
184 #[stable(feature = "rust1", since = "1.0.0")]
185 pub use self::function::{Fn, FnMut, FnOnce};
186
187 #[stable(feature = "rust1", since = "1.0.0")]
188 pub use self::index::{Index, IndexMut};
189
190 #[stable(feature = "rust1", since = "1.0.0")]
191 pub use self::range::{Range, RangeFrom, RangeFull, RangeTo};
192
193 #[stable(feature = "inclusive_range", since = "1.26.0")]
194 pub use self::range::{RangeInclusive, RangeToInclusive, RangeBounds, Bound};
195
196 #[unstable(feature = "try_trait", issue = "42327")]
197 pub use self::try::Try;
198
199 #[unstable(feature = "generator_trait", issue = "43122")]
200 pub use self::generator::{Generator, GeneratorState};
201
202 #[unstable(feature = "coerce_unsized", issue = "27732")]
203 pub use self::unsize::CoerceUnsized;
204
205 #[unstable(feature = "dispatch_from_dyn", issue = "0")]
206 pub use self::unsize::DispatchFromDyn;