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