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