]> git.lizzy.rs Git - rust.git/blob - library/core/src/ops/function.rs
Rollup merge of #102483 - spastorino:create-defs-on-lowering, r=cjgillot
[rust.git] / library / core / src / 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 /// [function pointers]: fn
32 /// [nomicon]: ../../nomicon/hrtb.html
33 ///
34 /// # Examples
35 ///
36 /// ## Calling a closure
37 ///
38 /// ```
39 /// let square = |x| x * x;
40 /// assert_eq!(square(5), 25);
41 /// ```
42 ///
43 /// ## Using a `Fn` parameter
44 ///
45 /// ```
46 /// fn call_with_one<F>(func: F) -> usize
47 ///     where F: Fn(usize) -> usize {
48 ///     func(1)
49 /// }
50 ///
51 /// let double = |x| x * 2;
52 /// assert_eq!(call_with_one(double), 2);
53 /// ```
54 #[lang = "fn"]
55 #[stable(feature = "rust1", since = "1.0.0")]
56 #[rustc_diagnostic_item = "Fn"]
57 #[rustc_paren_sugar]
58 #[rustc_on_unimplemented(
59     on(
60         Args = "()",
61         note = "wrap the `{Self}` in a closure with no arguments: `|| {{ /* code */ }}`"
62     ),
63     on(
64         _Self = "unsafe fn",
65         note = "unsafe function cannot be called generically without an unsafe block",
66         // SAFETY: tidy is not smart enough to tell that the below unsafe block is a string
67         label = "call the function in a closure: `|| unsafe {{ /* code */ }}`"
68     ),
69     message = "expected a `{Fn}<{Args}>` closure, found `{Self}`",
70     label = "expected an `Fn<{Args}>` closure, found `{Self}`"
71 )]
72 #[fundamental] // so that regex can rely that `&str: !FnMut`
73 #[must_use = "closures are lazy and do nothing unless called"]
74 #[cfg_attr(not(bootstrap), const_trait)]
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/ch13-01-closures.html
108 /// [function pointers]: fn
109 /// [nomicon]: ../../nomicon/hrtb.html
110 ///
111 /// # Examples
112 ///
113 /// ## Calling a mutably capturing closure
114 ///
115 /// ```
116 /// let mut x = 5;
117 /// {
118 ///     let mut square_x = || x *= x;
119 ///     square_x();
120 /// }
121 /// assert_eq!(x, 25);
122 /// ```
123 ///
124 /// ## Using a `FnMut` parameter
125 ///
126 /// ```
127 /// fn do_twice<F>(mut func: F)
128 ///     where F: FnMut()
129 /// {
130 ///     func();
131 ///     func();
132 /// }
133 ///
134 /// let mut x: usize = 1;
135 /// {
136 ///     let add_two_to_x = || x += 2;
137 ///     do_twice(add_two_to_x);
138 /// }
139 ///
140 /// assert_eq!(x, 5);
141 /// ```
142 #[lang = "fn_mut"]
143 #[stable(feature = "rust1", since = "1.0.0")]
144 #[rustc_diagnostic_item = "FnMut"]
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 #[cfg_attr(not(bootstrap), const_trait)]
163 pub trait FnMut<Args>: 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_diagnostic_item = "FnOnce"]
225 #[rustc_paren_sugar]
226 #[rustc_on_unimplemented(
227     on(
228         Args = "()",
229         note = "wrap the `{Self}` in a closure with no arguments: `|| {{ /* code */ }}`"
230     ),
231     on(
232         _Self = "unsafe fn",
233         note = "unsafe function cannot be called generically without an unsafe block",
234         // SAFETY: tidy is not smart enough to tell that the below unsafe block is a string
235         label = "call the function in a closure: `|| unsafe {{ /* code */ }}`"
236     ),
237     message = "expected a `{FnOnce}<{Args}>` closure, found `{Self}`",
238     label = "expected an `FnOnce<{Args}>` closure, found `{Self}`"
239 )]
240 #[fundamental] // so that regex can rely that `&str: !FnMut`
241 #[must_use = "closures are lazy and do nothing unless called"]
242 #[cfg_attr(not(bootstrap), const_trait)]
243 pub trait FnOnce<Args> {
244     /// The returned type after the call operator is used.
245     #[lang = "fn_once_output"]
246     #[stable(feature = "fn_once_output", since = "1.12.0")]
247     type Output;
248
249     /// Performs the call operation.
250     #[unstable(feature = "fn_traits", issue = "29625")]
251     extern "rust-call" fn call_once(self, args: Args) -> Self::Output;
252 }
253
254 mod impls {
255     #[stable(feature = "rust1", since = "1.0.0")]
256     #[rustc_const_unstable(feature = "const_fn_trait_ref_impls", issue = "101803")]
257     impl<A, F: ?Sized> const Fn<A> for &F
258     where
259         F: ~const Fn<A>,
260     {
261         extern "rust-call" fn call(&self, args: A) -> F::Output {
262             (**self).call(args)
263         }
264     }
265
266     #[stable(feature = "rust1", since = "1.0.0")]
267     #[rustc_const_unstable(feature = "const_fn_trait_ref_impls", issue = "101803")]
268     impl<A, F: ?Sized> const FnMut<A> for &F
269     where
270         F: ~const Fn<A>,
271     {
272         extern "rust-call" fn call_mut(&mut self, args: A) -> F::Output {
273             (**self).call(args)
274         }
275     }
276
277     #[stable(feature = "rust1", since = "1.0.0")]
278     #[rustc_const_unstable(feature = "const_fn_trait_ref_impls", issue = "101803")]
279     impl<A, F: ?Sized> const FnOnce<A> for &F
280     where
281         F: ~const Fn<A>,
282     {
283         type Output = F::Output;
284
285         extern "rust-call" fn call_once(self, args: A) -> F::Output {
286             (*self).call(args)
287         }
288     }
289
290     #[stable(feature = "rust1", since = "1.0.0")]
291     #[rustc_const_unstable(feature = "const_fn_trait_ref_impls", issue = "101803")]
292     impl<A, F: ?Sized> const FnMut<A> for &mut F
293     where
294         F: ~const FnMut<A>,
295     {
296         extern "rust-call" fn call_mut(&mut self, args: A) -> F::Output {
297             (*self).call_mut(args)
298         }
299     }
300
301     #[stable(feature = "rust1", since = "1.0.0")]
302     #[rustc_const_unstable(feature = "const_fn_trait_ref_impls", issue = "101803")]
303     impl<A, F: ?Sized> const FnOnce<A> for &mut F
304     where
305         F: ~const FnMut<A>,
306     {
307         type Output = F::Output;
308         extern "rust-call" fn call_once(self, args: A) -> F::Output {
309             (*self).call_mut(args)
310         }
311     }
312 }