]> git.lizzy.rs Git - rust.git/blob - src/libcore/ops/function.rs
Various minor/cosmetic improvements to code
[rust.git] / src / libcore / ops / function.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 /// The version of the call operator that takes an immutable receiver.
12 ///
13 /// Instances of `Fn` can be called repeatedly without mutating state.
14 ///
15 /// *This trait (`Fn`) is not to be confused with [function pointers][]
16 /// (`fn`).*
17 ///
18 /// `Fn` is implemented automatically by closures which only take immutable
19 /// references to captured variables or don't capture anything at all, as well
20 /// as (safe) [function pointers][] (with some caveats, see their documentation
21 /// for more details). Additionally, for any type `F` that implements `Fn`, `&F`
22 /// implements `Fn`, too.
23 ///
24 /// Since both [`FnMut`] and [`FnOnce`] are supertraits of `Fn`, any
25 /// instance of `Fn` can be used as a parameter where a [`FnMut`] or [`FnOnce`]
26 /// is expected.
27 ///
28 /// Use `Fn` as a bound when you want to accept a parameter of function-like
29 /// type and need to call it repeatedly and without mutating state (e.g., when
30 /// calling it concurrently). If you do not need such strict requirements, use
31 /// [`FnMut`] or [`FnOnce`] as bounds.
32 ///
33 /// See the [chapter on closures in *The Rust Programming Language*][book] for
34 /// some more information on this topic.
35 ///
36 /// Also of note is the special syntax for `Fn` traits (e.g.
37 /// `Fn(usize, bool) -> usize`). Those interested in the technical details of
38 /// this can refer to [the relevant section in the *Rustonomicon*][nomicon].
39 ///
40 /// [book]: ../../book/second-edition/ch13-01-closures.html
41 /// [`FnMut`]: trait.FnMut.html
42 /// [`FnOnce`]: trait.FnOnce.html
43 /// [function pointers]: ../../std/primitive.fn.html
44 /// [nomicon]: ../../nomicon/hrtb.html
45 ///
46 /// # Examples
47 ///
48 /// ## Calling a closure
49 ///
50 /// ```
51 /// let square = |x| x * x;
52 /// assert_eq!(square(5), 25);
53 /// ```
54 ///
55 /// ## Using a `Fn` parameter
56 ///
57 /// ```
58 /// fn call_with_one<F>(func: F) -> usize
59 ///     where F: Fn(usize) -> usize {
60 ///     func(1)
61 /// }
62 ///
63 /// let double = |x| x * 2;
64 /// assert_eq!(call_with_one(double), 2);
65 /// ```
66 #[lang = "fn"]
67 #[stable(feature = "rust1", since = "1.0.0")]
68 #[rustc_paren_sugar]
69 #[rustc_on_unimplemented(
70     on(Args="()", note="wrap the `{Self}` in a closure with no arguments: `|| {{ /* code */ }}"),
71     message="expected a `{Fn}<{Args}>` closure, found `{Self}`",
72     label="expected an `Fn<{Args}>` closure, found `{Self}`",
73 )]
74 #[fundamental] // so that regex can rely that `&str: !FnMut`
75 pub trait Fn<Args> : FnMut<Args> {
76     /// Performs the call operation.
77     #[unstable(feature = "fn_traits", issue = "29625")]
78     extern "rust-call" fn call(&self, args: Args) -> Self::Output;
79 }
80
81 /// The version of the call operator that takes a mutable receiver.
82 ///
83 /// Instances of `FnMut` can be called repeatedly and may mutate state.
84 ///
85 /// `FnMut` is implemented automatically by closures which take mutable
86 /// references to captured variables, as well as all types that implement
87 /// [`Fn`], e.g., (safe) [function pointers][] (since `FnMut` is a supertrait of
88 /// [`Fn`]). Additionally, for any type `F` that implements `FnMut`, `&mut F`
89 /// implements `FnMut`, too.
90 ///
91 /// Since [`FnOnce`] is a supertrait of `FnMut`, any instance of `FnMut` can be
92 /// used where a [`FnOnce`] is expected, and since [`Fn`] is a subtrait of
93 /// `FnMut`, any instance of [`Fn`] can be used where `FnMut` is expected.
94 ///
95 /// Use `FnMut` as a bound when you want to accept a parameter of function-like
96 /// type and need to call it repeatedly, while allowing it to mutate state.
97 /// If you don't want the parameter to mutate state, use [`Fn`] as a
98 /// bound; if you don't need to call it repeatedly, use [`FnOnce`].
99 ///
100 /// See the [chapter on closures in *The Rust Programming Language*][book] for
101 /// some more information on this topic.
102 ///
103 /// Also of note is the special syntax for `Fn` traits (e.g.
104 /// `Fn(usize, bool) -> usize`). Those interested in the technical details of
105 /// this can refer to [the relevant section in the *Rustonomicon*][nomicon].
106 ///
107 /// [book]: ../../book/second-edition/ch13-01-closures.html
108 /// [`Fn`]: trait.Fn.html
109 /// [`FnOnce`]: trait.FnOnce.html
110 /// [function pointers]: ../../std/primitive.fn.html
111 /// [nomicon]: ../../nomicon/hrtb.html
112 ///
113 /// # Examples
114 ///
115 /// ## Calling a mutably capturing closure
116 ///
117 /// ```
118 /// let mut x = 5;
119 /// {
120 ///     let mut square_x = || x *= x;
121 ///     square_x();
122 /// }
123 /// assert_eq!(x, 25);
124 /// ```
125 ///
126 /// ## Using a `FnMut` parameter
127 ///
128 /// ```
129 /// fn do_twice<F>(mut func: F)
130 ///     where F: FnMut()
131 /// {
132 ///     func();
133 ///     func();
134 /// }
135 ///
136 /// let mut x: usize = 1;
137 /// {
138 ///     let add_two_to_x = || x += 2;
139 ///     do_twice(add_two_to_x);
140 /// }
141 ///
142 /// assert_eq!(x, 5);
143 /// ```
144 #[lang = "fn_mut"]
145 #[stable(feature = "rust1", since = "1.0.0")]
146 #[rustc_paren_sugar]
147 #[rustc_on_unimplemented(
148     on(Args="()", note="wrap the `{Self}` in a closure with no arguments: `|| {{ /* code */ }}"),
149     message="expected a `{FnMut}<{Args}>` closure, found `{Self}`",
150     label="expected an `FnMut<{Args}>` closure, found `{Self}`",
151 )]
152 #[fundamental] // so that regex can rely that `&str: !FnMut`
153 pub trait FnMut<Args> : FnOnce<Args> {
154     /// Performs the call operation.
155     #[unstable(feature = "fn_traits", issue = "29625")]
156     extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output;
157 }
158
159 /// The version of the call operator that takes a by-value receiver.
160 ///
161 /// Instances of `FnOnce` can be called, but might not be callable multiple
162 /// times. Because of this, if the only thing known about a type is that it
163 /// implements `FnOnce`, it can only be called once.
164 ///
165 /// `FnOnce` is implemented automatically by closure that might consume captured
166 /// variables, as well as all types that implement [`FnMut`], e.g., (safe)
167 /// [function pointers][] (since `FnOnce` is a supertrait of [`FnMut`]).
168 ///
169 /// Since both [`Fn`] and [`FnMut`] are subtraits of `FnOnce`, any instance of
170 /// [`Fn`] or [`FnMut`] can be used where a `FnOnce` is expected.
171 ///
172 /// Use `FnOnce` as a bound when you want to accept a parameter of function-like
173 /// type and only need to call it once. If you need to call the parameter
174 /// repeatedly, use [`FnMut`] as a bound; if you also need it to not mutate
175 /// state, use [`Fn`].
176 ///
177 /// See the [chapter on closures in *The Rust Programming Language*][book] for
178 /// some more information on this topic.
179 ///
180 /// Also of note is the special syntax for `Fn` traits (e.g.
181 /// `Fn(usize, bool) -> usize`). Those interested in the technical details of
182 /// this can refer to [the relevant section in the *Rustonomicon*][nomicon].
183 ///
184 /// [book]: ../../book/second-edition/ch13-01-closures.html
185 /// [`Fn`]: trait.Fn.html
186 /// [`FnMut`]: trait.FnMut.html
187 /// [function pointers]: ../../std/primitive.fn.html
188 /// [nomicon]: ../../nomicon/hrtb.html
189 ///
190 /// # Examples
191 ///
192 /// ## Calling a by-value closure
193 ///
194 /// ```
195 /// let x = 5;
196 /// let square_x = move || x * x;
197 /// assert_eq!(square_x(), 25);
198 /// ```
199 ///
200 /// ## Using a `FnOnce` parameter
201 ///
202 /// ```
203 /// fn consume_with_relish<F>(func: F)
204 ///     where F: FnOnce() -> String
205 /// {
206 ///     // `func` consumes its captured variables, so it cannot be run more
207 ///     // than once.
208 ///     println!("Consumed: {}", func());
209 ///
210 ///     println!("Delicious!");
211 ///
212 ///     // Attempting to invoke `func()` again will throw a `use of moved
213 ///     // value` error for `func`.
214 /// }
215 ///
216 /// let x = String::from("x");
217 /// let consume_and_return_x = move || x;
218 /// consume_with_relish(consume_and_return_x);
219 ///
220 /// // `consume_and_return_x` can no longer be invoked at this point
221 /// ```
222 #[lang = "fn_once"]
223 #[stable(feature = "rust1", since = "1.0.0")]
224 #[rustc_paren_sugar]
225 #[rustc_on_unimplemented(
226     on(Args="()", note="wrap the `{Self}` in a closure with no arguments: `|| {{ /* code */ }}"),
227     message="expected a `{FnOnce}<{Args}>` closure, found `{Self}`",
228     label="expected an `FnOnce<{Args}>` closure, found `{Self}`",
229 )]
230 #[fundamental] // so that regex can rely that `&str: !FnMut`
231 pub trait FnOnce<Args> {
232     /// The returned type after the call operator is used.
233     #[stable(feature = "fn_once_output", since = "1.12.0")]
234     type Output;
235
236     /// Performs the call operation.
237     #[unstable(feature = "fn_traits", issue = "29625")]
238     extern "rust-call" fn call_once(self, args: Args) -> Self::Output;
239 }
240
241 mod impls {
242     #[stable(feature = "rust1", since = "1.0.0")]
243     impl<A,F:?Sized> Fn<A> for &F
244         where F : Fn<A>
245     {
246         extern "rust-call" fn call(&self, args: A) -> F::Output {
247             (**self).call(args)
248         }
249     }
250
251     #[stable(feature = "rust1", since = "1.0.0")]
252     impl<A,F:?Sized> FnMut<A> for &F
253         where F : Fn<A>
254     {
255         extern "rust-call" fn call_mut(&mut self, args: A) -> F::Output {
256             (**self).call(args)
257         }
258     }
259
260     #[stable(feature = "rust1", since = "1.0.0")]
261     impl<A,F:?Sized> FnOnce<A> for &F
262         where F : Fn<A>
263     {
264         type Output = F::Output;
265
266         extern "rust-call" fn call_once(self, args: A) -> F::Output {
267             (*self).call(args)
268         }
269     }
270
271     #[stable(feature = "rust1", since = "1.0.0")]
272     impl<A,F:?Sized> FnMut<A> for &mut F
273         where F : FnMut<A>
274     {
275         extern "rust-call" fn call_mut(&mut self, args: A) -> F::Output {
276             (*self).call_mut(args)
277         }
278     }
279
280     #[stable(feature = "rust1", since = "1.0.0")]
281     impl<A,F:?Sized> FnOnce<A> for &mut F
282         where F : FnMut<A>
283     {
284         type Output = F::Output;
285         extern "rust-call" fn call_once(self, args: A) -> F::Output {
286             (*self).call_mut(args)
287         }
288     }
289 }