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