]> git.lizzy.rs Git - rust.git/blob - library/core/src/ops/function.rs
Added Tracking Issue number.
[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 pub trait Fn<Args>: FnMut<Args> {
75     /// Performs the call operation.
76     #[unstable(feature = "fn_traits", issue = "29625")]
77     extern "rust-call" fn call(&self, args: Args) -> Self::Output;
78 }
79
80 /// The version of the call operator that takes a mutable receiver.
81 ///
82 /// Instances of `FnMut` can be called repeatedly and may mutate state.
83 ///
84 /// `FnMut` is implemented automatically by closures which take mutable
85 /// references to captured variables, as well as all types that implement
86 /// [`Fn`], e.g., (safe) [function pointers] (since `FnMut` is a supertrait of
87 /// [`Fn`]). Additionally, for any type `F` that implements `FnMut`, `&mut F`
88 /// implements `FnMut`, too.
89 ///
90 /// Since [`FnOnce`] is a supertrait of `FnMut`, any instance of `FnMut` can be
91 /// used where a [`FnOnce`] is expected, and since [`Fn`] is a subtrait of
92 /// `FnMut`, any instance of [`Fn`] can be used where `FnMut` is expected.
93 ///
94 /// Use `FnMut` as a bound when you want to accept a parameter of function-like
95 /// type and need to call it repeatedly, while allowing it to mutate state.
96 /// If you don't want the parameter to mutate state, use [`Fn`] as a
97 /// bound; if you don't need to call it repeatedly, use [`FnOnce`].
98 ///
99 /// See the [chapter on closures in *The Rust Programming Language*][book] for
100 /// some more information on this topic.
101 ///
102 /// Also of note is the special syntax for `Fn` traits (e.g.
103 /// `Fn(usize, bool) -> usize`). Those interested in the technical details of
104 /// this can refer to [the relevant section in the *Rustonomicon*][nomicon].
105 ///
106 /// [book]: ../../book/ch13-01-closures.html
107 /// [function pointers]: fn
108 /// [nomicon]: ../../nomicon/hrtb.html
109 ///
110 /// # Examples
111 ///
112 /// ## Calling a mutably capturing closure
113 ///
114 /// ```
115 /// let mut x = 5;
116 /// {
117 ///     let mut square_x = || x *= x;
118 ///     square_x();
119 /// }
120 /// assert_eq!(x, 25);
121 /// ```
122 ///
123 /// ## Using a `FnMut` parameter
124 ///
125 /// ```
126 /// fn do_twice<F>(mut func: F)
127 ///     where F: FnMut()
128 /// {
129 ///     func();
130 ///     func();
131 /// }
132 ///
133 /// let mut x: usize = 1;
134 /// {
135 ///     let add_two_to_x = || x += 2;
136 ///     do_twice(add_two_to_x);
137 /// }
138 ///
139 /// assert_eq!(x, 5);
140 /// ```
141 #[lang = "fn_mut"]
142 #[stable(feature = "rust1", since = "1.0.0")]
143 #[rustc_diagnostic_item = "FnMut"]
144 #[rustc_paren_sugar]
145 #[rustc_on_unimplemented(
146     on(
147         Args = "()",
148         note = "wrap the `{Self}` in a closure with no arguments: `|| {{ /* code */ }}`"
149     ),
150     on(
151         _Self = "unsafe fn",
152         note = "unsafe function cannot be called generically without an unsafe block",
153         // SAFETY: tidy is not smart enough to tell that the below unsafe block is a string
154         label = "call the function in a closure: `|| unsafe {{ /* code */ }}`"
155     ),
156     message = "expected a `{FnMut}<{Args}>` closure, found `{Self}`",
157     label = "expected an `FnMut<{Args}>` closure, found `{Self}`"
158 )]
159 #[fundamental] // so that regex can rely that `&str: !FnMut`
160 #[must_use = "closures are lazy and do nothing unless called"]
161 pub trait FnMut<Args>: FnOnce<Args> {
162     /// Performs the call operation.
163     #[unstable(feature = "fn_traits", issue = "29625")]
164     extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output;
165 }
166
167 /// The version of the call operator that takes a by-value receiver.
168 ///
169 /// Instances of `FnOnce` can be called, but might not be callable multiple
170 /// times. Because of this, if the only thing known about a type is that it
171 /// implements `FnOnce`, it can only be called once.
172 ///
173 /// `FnOnce` is implemented automatically by closures that might consume captured
174 /// variables, as well as all types that implement [`FnMut`], e.g., (safe)
175 /// [function pointers] (since `FnOnce` is a supertrait of [`FnMut`]).
176 ///
177 /// Since both [`Fn`] and [`FnMut`] are subtraits of `FnOnce`, any instance of
178 /// [`Fn`] or [`FnMut`] can be used where a `FnOnce` is expected.
179 ///
180 /// Use `FnOnce` as a bound when you want to accept a parameter of function-like
181 /// type and only need to call it once. If you need to call the parameter
182 /// repeatedly, use [`FnMut`] as a bound; if you also need it to not mutate
183 /// state, use [`Fn`].
184 ///
185 /// See the [chapter on closures in *The Rust Programming Language*][book] for
186 /// some more information on this topic.
187 ///
188 /// Also of note is the special syntax for `Fn` traits (e.g.
189 /// `Fn(usize, bool) -> usize`). Those interested in the technical details of
190 /// this can refer to [the relevant section in the *Rustonomicon*][nomicon].
191 ///
192 /// [book]: ../../book/ch13-01-closures.html
193 /// [function pointers]: fn
194 /// [nomicon]: ../../nomicon/hrtb.html
195 ///
196 /// # Examples
197 ///
198 /// ## Using a `FnOnce` parameter
199 ///
200 /// ```
201 /// fn consume_with_relish<F>(func: F)
202 ///     where F: FnOnce() -> String
203 /// {
204 ///     // `func` consumes its captured variables, so it cannot be run more
205 ///     // than once.
206 ///     println!("Consumed: {}", func());
207 ///
208 ///     println!("Delicious!");
209 ///
210 ///     // Attempting to invoke `func()` again will throw a `use of moved
211 ///     // value` error for `func`.
212 /// }
213 ///
214 /// let x = String::from("x");
215 /// let consume_and_return_x = move || x;
216 /// consume_with_relish(consume_and_return_x);
217 ///
218 /// // `consume_and_return_x` can no longer be invoked at this point
219 /// ```
220 #[lang = "fn_once"]
221 #[stable(feature = "rust1", since = "1.0.0")]
222 #[rustc_diagnostic_item = "FnOnce"]
223 #[rustc_paren_sugar]
224 #[rustc_on_unimplemented(
225     on(
226         Args = "()",
227         note = "wrap the `{Self}` in a closure with no arguments: `|| {{ /* code */ }}`"
228     ),
229     on(
230         _Self = "unsafe fn",
231         note = "unsafe function cannot be called generically without an unsafe block",
232         // SAFETY: tidy is not smart enough to tell that the below unsafe block is a string
233         label = "call the function in a closure: `|| unsafe {{ /* code */ }}`"
234     ),
235     message = "expected a `{FnOnce}<{Args}>` closure, found `{Self}`",
236     label = "expected an `FnOnce<{Args}>` closure, found `{Self}`"
237 )]
238 #[fundamental] // so that regex can rely that `&str: !FnMut`
239 #[must_use = "closures are lazy and do nothing unless called"]
240 pub trait FnOnce<Args> {
241     /// The returned type after the call operator is used.
242     #[lang = "fn_once_output"]
243     #[stable(feature = "fn_once_output", since = "1.12.0")]
244     type Output;
245
246     /// Performs the call operation.
247     #[unstable(feature = "fn_traits", issue = "29625")]
248     extern "rust-call" fn call_once(self, args: Args) -> Self::Output;
249 }
250
251 mod impls {
252     #[stable(feature = "rust1", since = "1.0.0")]
253     #[rustc_const_unstable(feature = "const_fn_trait_ref_impls", issue = "101803")]
254     impl<A, F: ?Sized> const Fn<A> for &F
255     where
256         F: ~const Fn<A>,
257     {
258         extern "rust-call" fn call(&self, args: A) -> F::Output {
259             (**self).call(args)
260         }
261     }
262
263     #[stable(feature = "rust1", since = "1.0.0")]
264     #[rustc_const_unstable(feature = "const_fn_trait_ref_impls", issue = "101803")]
265     impl<A, F: ?Sized> const FnMut<A> for &F
266     where
267         F: ~const Fn<A>,
268     {
269         extern "rust-call" fn call_mut(&mut self, args: A) -> F::Output {
270             (**self).call(args)
271         }
272     }
273
274     #[stable(feature = "rust1", since = "1.0.0")]
275     #[rustc_const_unstable(feature = "const_fn_trait_ref_impls", issue = "101803")]
276     impl<A, F: ?Sized> const FnOnce<A> for &F
277     where
278         F: ~const Fn<A>,
279     {
280         type Output = F::Output;
281
282         extern "rust-call" fn call_once(self, args: A) -> F::Output {
283             (*self).call(args)
284         }
285     }
286
287     #[stable(feature = "rust1", since = "1.0.0")]
288     #[rustc_const_unstable(feature = "const_fn_trait_ref_impls", issue = "101803")]
289     impl<A, F: ?Sized> const FnMut<A> for &mut F
290     where
291         F: ~const FnMut<A>,
292     {
293         extern "rust-call" fn call_mut(&mut self, args: A) -> F::Output {
294             (*self).call_mut(args)
295         }
296     }
297
298     #[stable(feature = "rust1", since = "1.0.0")]
299     #[rustc_const_unstable(feature = "const_fn_trait_ref_impls", issue = "101803")]
300     impl<A, F: ?Sized> const FnOnce<A> for &mut F
301     where
302         F: ~const FnMut<A>,
303     {
304         type Output = F::Output;
305         extern "rust-call" fn call_once(self, args: A) -> F::Output {
306             (*self).call_mut(args)
307         }
308     }
309 }