]> git.proxmox.com Git - rustc.git/blob - library/core/src/ops/function.rs
New upstream version 1.68.2+dfsg1
[rustc.git] / library / core / src / ops / function.rs
1 use crate::marker::Tuple;
2
3 /// The version of the call operator that takes an immutable receiver.
4 ///
5 /// Instances of `Fn` can be called repeatedly without mutating state.
6 ///
7 /// *This trait (`Fn`) is not to be confused with [function pointers]
8 /// (`fn`).*
9 ///
10 /// `Fn` is implemented automatically by closures which only take immutable
11 /// references to captured variables or don't capture anything at all, as well
12 /// as (safe) [function pointers] (with some caveats, see their documentation
13 /// for more details). Additionally, for any type `F` that implements `Fn`, `&F`
14 /// implements `Fn`, too.
15 ///
16 /// Since both [`FnMut`] and [`FnOnce`] are supertraits of `Fn`, any
17 /// instance of `Fn` can be used as a parameter where a [`FnMut`] or [`FnOnce`]
18 /// is expected.
19 ///
20 /// Use `Fn` as a bound when you want to accept a parameter of function-like
21 /// type and need to call it repeatedly and without mutating state (e.g., when
22 /// calling it concurrently). If you do not need such strict requirements, use
23 /// [`FnMut`] or [`FnOnce`] as bounds.
24 ///
25 /// See the [chapter on closures in *The Rust Programming Language*][book] for
26 /// some more information on this topic.
27 ///
28 /// Also of note is the special syntax for `Fn` traits (e.g.
29 /// `Fn(usize, bool) -> usize`). Those interested in the technical details of
30 /// this can refer to [the relevant section in the *Rustonomicon*][nomicon].
31 ///
32 /// [book]: ../../book/ch13-01-closures.html
33 /// [function pointers]: fn
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 on(
65 _Self = "unsafe fn",
66 note = "unsafe function cannot be called generically without an unsafe block",
67 // SAFETY: tidy is not smart enough to tell that the below unsafe block is a string
68 label = "call the function in a closure: `|| unsafe {{ /* code */ }}`"
69 ),
70 message = "expected a `{Fn}<{Args}>` closure, found `{Self}`",
71 label = "expected an `Fn<{Args}>` closure, found `{Self}`"
72 )]
73 #[fundamental] // so that regex can rely that `&str: !FnMut`
74 #[must_use = "closures are lazy and do nothing unless called"]
75 #[const_trait]
76 pub trait Fn<Args: Tuple>: FnMut<Args> {
77 /// Performs the call operation.
78 #[unstable(feature = "fn_traits", issue = "29625")]
79 extern "rust-call" fn call(&self, args: Args) -> Self::Output;
80 }
81
82 /// The version of the call operator that takes a mutable receiver.
83 ///
84 /// Instances of `FnMut` can be called repeatedly and may mutate state.
85 ///
86 /// `FnMut` is implemented automatically by closures which take mutable
87 /// references to captured variables, as well as all types that implement
88 /// [`Fn`], e.g., (safe) [function pointers] (since `FnMut` is a supertrait of
89 /// [`Fn`]). Additionally, for any type `F` that implements `FnMut`, `&mut F`
90 /// implements `FnMut`, too.
91 ///
92 /// Since [`FnOnce`] is a supertrait of `FnMut`, any instance of `FnMut` can be
93 /// used where a [`FnOnce`] is expected, and since [`Fn`] is a subtrait of
94 /// `FnMut`, any instance of [`Fn`] can be used where `FnMut` is expected.
95 ///
96 /// Use `FnMut` as a bound when you want to accept a parameter of function-like
97 /// type and need to call it repeatedly, while allowing it to mutate state.
98 /// If you don't want the parameter to mutate state, use [`Fn`] as a
99 /// bound; if you don't need to call it repeatedly, use [`FnOnce`].
100 ///
101 /// See the [chapter on closures in *The Rust Programming Language*][book] for
102 /// some more information on this topic.
103 ///
104 /// Also of note is the special syntax for `Fn` traits (e.g.
105 /// `Fn(usize, bool) -> usize`). Those interested in the technical details of
106 /// this can refer to [the relevant section in the *Rustonomicon*][nomicon].
107 ///
108 /// [book]: ../../book/ch13-01-closures.html
109 /// [function pointers]: fn
110 /// [nomicon]: ../../nomicon/hrtb.html
111 ///
112 /// # Examples
113 ///
114 /// ## Calling a mutably capturing closure
115 ///
116 /// ```
117 /// let mut x = 5;
118 /// {
119 /// let mut square_x = || x *= x;
120 /// square_x();
121 /// }
122 /// assert_eq!(x, 25);
123 /// ```
124 ///
125 /// ## Using a `FnMut` parameter
126 ///
127 /// ```
128 /// fn do_twice<F>(mut func: F)
129 /// where F: FnMut()
130 /// {
131 /// func();
132 /// func();
133 /// }
134 ///
135 /// let mut x: usize = 1;
136 /// {
137 /// let add_two_to_x = || x += 2;
138 /// do_twice(add_two_to_x);
139 /// }
140 ///
141 /// assert_eq!(x, 5);
142 /// ```
143 #[lang = "fn_mut"]
144 #[stable(feature = "rust1", since = "1.0.0")]
145 #[rustc_paren_sugar]
146 #[rustc_on_unimplemented(
147 on(
148 Args = "()",
149 note = "wrap the `{Self}` in a closure with no arguments: `|| {{ /* code */ }}`"
150 ),
151 on(
152 _Self = "unsafe fn",
153 note = "unsafe function cannot be called generically without an unsafe block",
154 // SAFETY: tidy is not smart enough to tell that the below unsafe block is a string
155 label = "call the function in a closure: `|| unsafe {{ /* code */ }}`"
156 ),
157 message = "expected a `{FnMut}<{Args}>` closure, found `{Self}`",
158 label = "expected an `FnMut<{Args}>` closure, found `{Self}`"
159 )]
160 #[fundamental] // so that regex can rely that `&str: !FnMut`
161 #[must_use = "closures are lazy and do nothing unless called"]
162 #[const_trait]
163 pub trait FnMut<Args: Tuple>: FnOnce<Args> {
164 /// Performs the call operation.
165 #[unstable(feature = "fn_traits", issue = "29625")]
166 extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output;
167 }
168
169 /// The version of the call operator that takes a by-value receiver.
170 ///
171 /// Instances of `FnOnce` can be called, but might not be callable multiple
172 /// times. Because of this, if the only thing known about a type is that it
173 /// implements `FnOnce`, it can only be called once.
174 ///
175 /// `FnOnce` is implemented automatically by closures that might consume captured
176 /// variables, as well as all types that implement [`FnMut`], e.g., (safe)
177 /// [function pointers] (since `FnOnce` is a supertrait of [`FnMut`]).
178 ///
179 /// Since both [`Fn`] and [`FnMut`] are subtraits of `FnOnce`, any instance of
180 /// [`Fn`] or [`FnMut`] can be used where a `FnOnce` is expected.
181 ///
182 /// Use `FnOnce` as a bound when you want to accept a parameter of function-like
183 /// type and only need to call it once. If you need to call the parameter
184 /// repeatedly, use [`FnMut`] as a bound; if you also need it to not mutate
185 /// state, use [`Fn`].
186 ///
187 /// See the [chapter on closures in *The Rust Programming Language*][book] for
188 /// some more information on this topic.
189 ///
190 /// Also of note is the special syntax for `Fn` traits (e.g.
191 /// `Fn(usize, bool) -> usize`). Those interested in the technical details of
192 /// this can refer to [the relevant section in the *Rustonomicon*][nomicon].
193 ///
194 /// [book]: ../../book/ch13-01-closures.html
195 /// [function pointers]: fn
196 /// [nomicon]: ../../nomicon/hrtb.html
197 ///
198 /// # Examples
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(
227 Args = "()",
228 note = "wrap the `{Self}` in a closure with no arguments: `|| {{ /* code */ }}`"
229 ),
230 on(
231 _Self = "unsafe fn",
232 note = "unsafe function cannot be called generically without an unsafe block",
233 // SAFETY: tidy is not smart enough to tell that the below unsafe block is a string
234 label = "call the function in a closure: `|| unsafe {{ /* code */ }}`"
235 ),
236 message = "expected a `{FnOnce}<{Args}>` closure, found `{Self}`",
237 label = "expected an `FnOnce<{Args}>` closure, found `{Self}`"
238 )]
239 #[fundamental] // so that regex can rely that `&str: !FnMut`
240 #[must_use = "closures are lazy and do nothing unless called"]
241 #[const_trait]
242 pub trait FnOnce<Args: Tuple> {
243 /// The returned type after the call operator is used.
244 #[lang = "fn_once_output"]
245 #[stable(feature = "fn_once_output", since = "1.12.0")]
246 type Output;
247
248 /// Performs the call operation.
249 #[unstable(feature = "fn_traits", issue = "29625")]
250 extern "rust-call" fn call_once(self, args: Args) -> Self::Output;
251 }
252
253 mod impls {
254 use crate::marker::Tuple;
255
256 #[stable(feature = "rust1", since = "1.0.0")]
257 #[rustc_const_unstable(feature = "const_fn_trait_ref_impls", issue = "101803")]
258 impl<A: Tuple, F: ?Sized> const Fn<A> for &F
259 where
260 F: ~const Fn<A>,
261 {
262 extern "rust-call" fn call(&self, args: A) -> F::Output {
263 (**self).call(args)
264 }
265 }
266
267 #[stable(feature = "rust1", since = "1.0.0")]
268 #[rustc_const_unstable(feature = "const_fn_trait_ref_impls", issue = "101803")]
269 impl<A: Tuple, F: ?Sized> const FnMut<A> for &F
270 where
271 F: ~const Fn<A>,
272 {
273 extern "rust-call" fn call_mut(&mut self, args: A) -> F::Output {
274 (**self).call(args)
275 }
276 }
277
278 #[stable(feature = "rust1", since = "1.0.0")]
279 #[rustc_const_unstable(feature = "const_fn_trait_ref_impls", issue = "101803")]
280 impl<A: Tuple, F: ?Sized> const FnOnce<A> for &F
281 where
282 F: ~const Fn<A>,
283 {
284 type Output = F::Output;
285
286 extern "rust-call" fn call_once(self, args: A) -> F::Output {
287 (*self).call(args)
288 }
289 }
290
291 #[stable(feature = "rust1", since = "1.0.0")]
292 #[rustc_const_unstable(feature = "const_fn_trait_ref_impls", issue = "101803")]
293 impl<A: Tuple, F: ?Sized> const FnMut<A> for &mut F
294 where
295 F: ~const FnMut<A>,
296 {
297 extern "rust-call" fn call_mut(&mut self, args: A) -> F::Output {
298 (*self).call_mut(args)
299 }
300 }
301
302 #[stable(feature = "rust1", since = "1.0.0")]
303 #[rustc_const_unstable(feature = "const_fn_trait_ref_impls", issue = "101803")]
304 impl<A: Tuple, F: ?Sized> const FnOnce<A> for &mut F
305 where
306 F: ~const FnMut<A>,
307 {
308 type Output = F::Output;
309 extern "rust-call" fn call_once(self, args: A) -> F::Output {
310 (*self).call_mut(args)
311 }
312 }
313 }