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