1 /// The version of the call operator that takes an immutable receiver.
3 /// Instances of `Fn` can be called repeatedly without mutating state.
5 /// *This trait (`Fn`) is not to be confused with [function pointers]
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.
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`]
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.
23 /// See the [chapter on closures in *The Rust Programming Language*][book] for
24 /// some more information on this topic.
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].
30 /// [book]: ../../book/ch13-01-closures.html
31 /// [function pointers]: fn
32 /// [nomicon]: ../../nomicon/hrtb.html
36 /// ## Calling a closure
39 /// let square = |x| x * x;
40 /// assert_eq!(square(5), 25);
43 /// ## Using a `Fn` parameter
46 /// fn call_with_one<F>(func: F) -> usize
47 /// where F: Fn(usize) -> usize {
51 /// let double = |x| x * 2;
52 /// assert_eq!(call_with_one(double), 2);
55 #[stable(feature = "rust1", since = "1.0.0")]
56 #[rustc_diagnostic_item = "Fn"]
58 #[rustc_on_unimplemented(
61 note = "wrap the `{Self}` in a closure with no arguments: `|| {{ /* code */ }}`"
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 */ }}`"
69 message = "expected a `{Fn}<{Args}>` closure, found `{Self}`",
70 label = "expected an `Fn<{Args}>` closure, found `{Self}`"
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;
81 /// The version of the call operator that takes a mutable receiver.
83 /// Instances of `FnMut` can be called repeatedly and may mutate state.
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.
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.
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`].
100 /// See the [chapter on closures in *The Rust Programming Language*][book] for
101 /// some more information on this topic.
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].
107 /// [book]: ../../book/ch13-01-closures.html
108 /// [function pointers]: fn
109 /// [nomicon]: ../../nomicon/hrtb.html
113 /// ## Calling a mutably capturing closure
118 /// let mut square_x = || x *= x;
121 /// assert_eq!(x, 25);
124 /// ## Using a `FnMut` parameter
127 /// fn do_twice<F>(mut func: F)
134 /// let mut x: usize = 1;
136 /// let add_two_to_x = || x += 2;
137 /// do_twice(add_two_to_x);
140 /// assert_eq!(x, 5);
143 #[stable(feature = "rust1", since = "1.0.0")]
144 #[rustc_diagnostic_item = "FnMut"]
146 #[rustc_on_unimplemented(
149 note = "wrap the `{Self}` in a closure with no arguments: `|| {{ /* code */ }}`"
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 */ }}`"
157 message = "expected a `{FnMut}<{Args}>` closure, found `{Self}`",
158 label = "expected an `FnMut<{Args}>` closure, found `{Self}`"
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;
169 /// The version of the call operator that takes a by-value receiver.
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.
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`]).
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.
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`].
187 /// See the [chapter on closures in *The Rust Programming Language*][book] for
188 /// some more information on this topic.
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].
194 /// [book]: ../../book/ch13-01-closures.html
195 /// [function pointers]: fn
196 /// [nomicon]: ../../nomicon/hrtb.html
200 /// ## Using a `FnOnce` parameter
203 /// fn consume_with_relish<F>(func: F)
204 /// where F: FnOnce() -> String
206 /// // `func` consumes its captured variables, so it cannot be run more
208 /// println!("Consumed: {}", func());
210 /// println!("Delicious!");
212 /// // Attempting to invoke `func()` again will throw a `use of moved
213 /// // value` error for `func`.
216 /// let x = String::from("x");
217 /// let consume_and_return_x = move || x;
218 /// consume_with_relish(consume_and_return_x);
220 /// // `consume_and_return_x` can no longer be invoked at this point
223 #[stable(feature = "rust1", since = "1.0.0")]
224 #[rustc_diagnostic_item = "FnOnce"]
226 #[rustc_on_unimplemented(
229 note = "wrap the `{Self}` in a closure with no arguments: `|| {{ /* code */ }}`"
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 */ }}`"
237 message = "expected a `{FnOnce}<{Args}>` closure, found `{Self}`",
238 label = "expected an `FnOnce<{Args}>` closure, found `{Self}`"
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")]
249 /// Performs the call operation.
250 #[unstable(feature = "fn_traits", issue = "29625")]
251 extern "rust-call" fn call_once(self, args: Args) -> Self::Output;
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
261 extern "rust-call" fn call(&self, args: A) -> F::Output {
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
272 extern "rust-call" fn call_mut(&mut self, args: A) -> F::Output {
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
283 type Output = F::Output;
285 extern "rust-call" fn call_once(self, args: A) -> F::Output {
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
296 extern "rust-call" fn call_mut(&mut self, args: A) -> F::Output {
297 (*self).call_mut(args)
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
307 type Output = F::Output;
308 extern "rust-call" fn call_once(self, args: A) -> F::Output {
309 (*self).call_mut(args)