]> git.lizzy.rs Git - rust.git/blob - src/libcore/ops/function.rs
Auto merge of #66322 - lzutao:consistent-result-map_or_else, r=dtolnay
[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 /// ## 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(Args="()", note="wrap the `{Self}` in a closure with no arguments: `|| {{ /* code */ }}"),
211     message="expected a `{FnOnce}<{Args}>` closure, found `{Self}`",
212     label="expected an `FnOnce<{Args}>` closure, found `{Self}`",
213 )]
214 #[fundamental] // so that regex can rely that `&str: !FnMut`
215 #[must_use = "closures are lazy and do nothing unless called"]
216 pub trait FnOnce<Args> {
217     /// The returned type after the call operator is used.
218     #[stable(feature = "fn_once_output", since = "1.12.0")]
219     type Output;
220
221     /// Performs the call operation.
222     #[unstable(feature = "fn_traits", issue = "29625")]
223     extern "rust-call" fn call_once(self, args: Args) -> Self::Output;
224 }
225
226 mod impls {
227     #[stable(feature = "rust1", since = "1.0.0")]
228     impl<A,F:?Sized> Fn<A> for &F
229         where F : Fn<A>
230     {
231         extern "rust-call" fn call(&self, args: A) -> F::Output {
232             (**self).call(args)
233         }
234     }
235
236     #[stable(feature = "rust1", since = "1.0.0")]
237     impl<A,F:?Sized> FnMut<A> for &F
238         where F : Fn<A>
239     {
240         extern "rust-call" fn call_mut(&mut self, args: A) -> F::Output {
241             (**self).call(args)
242         }
243     }
244
245     #[stable(feature = "rust1", since = "1.0.0")]
246     impl<A,F:?Sized> FnOnce<A> for &F
247         where F : Fn<A>
248     {
249         type Output = F::Output;
250
251         extern "rust-call" fn call_once(self, args: A) -> F::Output {
252             (*self).call(args)
253         }
254     }
255
256     #[stable(feature = "rust1", since = "1.0.0")]
257     impl<A,F:?Sized> FnMut<A> for &mut F
258         where F : FnMut<A>
259     {
260         extern "rust-call" fn call_mut(&mut self, args: A) -> F::Output {
261             (*self).call_mut(args)
262         }
263     }
264
265     #[stable(feature = "rust1", since = "1.0.0")]
266     impl<A,F:?Sized> FnOnce<A> for &mut F
267         where F : FnMut<A>
268     {
269         type Output = F::Output;
270         extern "rust-call" fn call_once(self, args: A) -> F::Output {
271             (*self).call_mut(args)
272         }
273     }
274 }