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 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;
80 /// The version of the call operator that takes a mutable receiver.
82 /// Instances of `FnMut` can be called repeatedly and may mutate state.
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.
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.
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`].
99 /// See the [chapter on closures in *The Rust Programming Language*][book] for
100 /// some more information on this topic.
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].
106 /// [book]: ../../book/ch13-01-closures.html
107 /// [function pointers]: fn
108 /// [nomicon]: ../../nomicon/hrtb.html
112 /// ## Calling a mutably capturing closure
117 /// let mut square_x = || x *= x;
120 /// assert_eq!(x, 25);
123 /// ## Using a `FnMut` parameter
126 /// fn do_twice<F>(mut func: F)
133 /// let mut x: usize = 1;
135 /// let add_two_to_x = || x += 2;
136 /// do_twice(add_two_to_x);
139 /// assert_eq!(x, 5);
142 #[stable(feature = "rust1", since = "1.0.0")]
143 #[rustc_diagnostic_item = "FnMut"]
145 #[rustc_on_unimplemented(
148 note = "wrap the `{Self}` in a closure with no arguments: `|| {{ /* code */ }}`"
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 */ }}`"
156 message = "expected a `{FnMut}<{Args}>` closure, found `{Self}`",
157 label = "expected an `FnMut<{Args}>` closure, found `{Self}`"
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;
167 /// The version of the call operator that takes a by-value receiver.
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.
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`]).
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.
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`].
185 /// See the [chapter on closures in *The Rust Programming Language*][book] for
186 /// some more information on this topic.
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].
192 /// [book]: ../../book/ch13-01-closures.html
193 /// [function pointers]: fn
194 /// [nomicon]: ../../nomicon/hrtb.html
198 /// ## Using a `FnOnce` parameter
201 /// fn consume_with_relish<F>(func: F)
202 /// where F: FnOnce() -> String
204 /// // `func` consumes its captured variables, so it cannot be run more
206 /// println!("Consumed: {}", func());
208 /// println!("Delicious!");
210 /// // Attempting to invoke `func()` again will throw a `use of moved
211 /// // value` error for `func`.
214 /// let x = String::from("x");
215 /// let consume_and_return_x = move || x;
216 /// consume_with_relish(consume_and_return_x);
218 /// // `consume_and_return_x` can no longer be invoked at this point
221 #[stable(feature = "rust1", since = "1.0.0")]
222 #[rustc_diagnostic_item = "FnOnce"]
224 #[rustc_on_unimplemented(
227 note = "wrap the `{Self}` in a closure with no arguments: `|| {{ /* code */ }}`"
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 */ }}`"
235 message = "expected a `{FnOnce}<{Args}>` closure, found `{Self}`",
236 label = "expected an `FnOnce<{Args}>` closure, found `{Self}`"
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")]
246 /// Performs the call operation.
247 #[unstable(feature = "fn_traits", issue = "29625")]
248 extern "rust-call" fn call_once(self, args: Args) -> Self::Output;
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
258 extern "rust-call" fn call(&self, args: A) -> F::Output {
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
269 extern "rust-call" fn call_mut(&mut self, args: A) -> F::Output {
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
280 type Output = F::Output;
282 extern "rust-call" fn call_once(self, args: A) -> F::Output {
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
293 extern "rust-call" fn call_mut(&mut self, args: A) -> F::Output {
294 (*self).call_mut(args)
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
304 type Output = F::Output;
305 extern "rust-call" fn call_once(self, args: A) -> F::Output {
306 (*self).call_mut(args)