]> git.proxmox.com Git - rustc.git/blob - src/doc/reference/src/items/functions.md
New upstream version 1.60.0+dfsg1
[rustc.git] / src / doc / reference / src / items / functions.md
1 # Functions
2
3 > **<sup>Syntax</sup>**\
4 > _Function_ :\
5 > &nbsp;&nbsp; _FunctionQualifiers_ `fn` [IDENTIFIER]&nbsp;[_GenericParams_]<sup>?</sup>\
6 > &nbsp;&nbsp; &nbsp;&nbsp; `(` _FunctionParameters_<sup>?</sup> `)`\
7 > &nbsp;&nbsp; &nbsp;&nbsp; _FunctionReturnType_<sup>?</sup> [_WhereClause_]<sup>?</sup>\
8 > &nbsp;&nbsp; &nbsp;&nbsp; ( [_BlockExpression_] | `;` )
9 >
10 > _FunctionQualifiers_ :\
11 > &nbsp;&nbsp; `const`<sup>?</sup> `async`[^async-edition]<sup>?</sup> `unsafe`<sup>?</sup> (`extern` _Abi_<sup>?</sup>)<sup>?</sup>
12 >
13 > _Abi_ :\
14 > &nbsp;&nbsp; [STRING_LITERAL] | [RAW_STRING_LITERAL]
15 >
16 > _FunctionParameters_ :\
17 > &nbsp;&nbsp; &nbsp;&nbsp; _SelfParam_ `,`<sup>?</sup>\
18 > &nbsp;&nbsp; | (_SelfParam_ `,`)<sup>?</sup> _FunctionParam_ (`,` _FunctionParam_)<sup>\*</sup> `,`<sup>?</sup>
19 >
20 > _SelfParam_ :\
21 > &nbsp;&nbsp; [_OuterAttribute_]<sup>\*</sup> ( _ShorthandSelf_ | _TypedSelf_ )
22 >
23 > _ShorthandSelf_ :\
24 > &nbsp;&nbsp; (`&` | `&` [_Lifetime_])<sup>?</sup> `mut`<sup>?</sup> `self`
25 >
26 > _TypedSelf_ :\
27 > &nbsp;&nbsp; `mut`<sup>?</sup> `self` `:` [_Type_]
28 >
29 > _FunctionParam_ :\
30 > &nbsp;&nbsp; [_OuterAttribute_]<sup>\*</sup> (
31 > _FunctionParamPattern_ | `...` | [_Type_] [^fn-param-2015]
32 > )
33 >
34 > _FunctionParamPattern_ :\
35 > &nbsp;&nbsp; [_PatternNoTopAlt_] `:` ( [_Type_] | `...` )
36 >
37 > _FunctionReturnType_ :\
38 > &nbsp;&nbsp; `->` [_Type_]
39 >
40 > [^async-edition]: The `async` qualifier is not allowed in the 2015 edition.
41 >
42 > [^fn-param-2015]: Function parameters with only a type are only allowed
43 > in an associated function of a [trait item] in the 2015 edition.
44
45 A _function_ consists of a [block], along with a name and a set of parameters.
46 Other than a name, all these are optional. Functions are declared with the
47 keyword `fn`. Functions may declare a set of *input* [*variables*][variables]
48 as parameters, through which the caller passes arguments into the function, and
49 the *output* [*type*][type] of the value the function will return to its caller
50 on completion.
51
52 When referred to, a _function_ yields a first-class *value* of the
53 corresponding zero-sized [*function item type*], which
54 when called evaluates to a direct call to the function.
55
56 For example, this is a simple function:
57 ```rust
58 fn answer_to_life_the_universe_and_everything() -> i32 {
59 return 42;
60 }
61 ```
62
63 ## Function parameters
64
65 As with `let` bindings, function parameters are irrefutable [patterns], so any
66 pattern that is valid in a let binding is also valid as a parameter:
67
68 ```rust
69 fn first((value, _): (i32, i32)) -> i32 { value }
70 ```
71
72 If the first parameter is a _SelfParam_, this indicates that the function is a
73 [method]. Functions with a self parameter may only appear as an [associated
74 function] in a [trait] or [implementation].
75
76 A parameter with the `...` token indicates a [variadic function], and may only
77 be used as the last parameter of an [external block] function. The variadic
78 parameter may have an optional identifier, such as `args: ...`.
79
80 ## Function body
81
82 The block of a function is conceptually wrapped in a block that binds the
83 argument patterns and then `return`s the value of the function's block. This
84 means that the tail expression of the block, if evaluated, ends up being
85 returned to the caller. As usual, an explicit return expression within
86 the body of the function will short-cut that implicit return, if reached.
87
88 For example, the function above behaves as if it was written as:
89
90 <!-- ignore: example expansion -->
91 ```rust,ignore
92 // argument_0 is the actual first argument passed from the caller
93 let (value, _) = argument_0;
94 return {
95 value
96 };
97 ```
98
99 Functions without a body block are terminated with a semicolon. This form
100 may only appear in a [trait] or [external block].
101
102 ## Generic functions
103
104 A _generic function_ allows one or more _parameterized types_ to appear in its
105 signature. Each type parameter must be explicitly declared in an
106 angle-bracket-enclosed and comma-separated list, following the function name.
107
108 ```rust
109 // foo is generic over A and B
110
111 fn foo<A, B>(x: A, y: B) {
112 # }
113 ```
114
115 Inside the function signature and body, the name of the type parameter can be
116 used as a type name. [Trait] bounds can be specified for type
117 parameters to allow methods with that trait to be called on values of that
118 type. This is specified using the `where` syntax:
119
120 ```rust
121 # use std::fmt::Debug;
122 fn foo<T>(x: T) where T: Debug {
123 # }
124 ```
125
126 When a generic function is referenced, its type is instantiated based on the
127 context of the reference. For example, calling the `foo` function here:
128
129 ```rust
130 use std::fmt::Debug;
131
132 fn foo<T>(x: &[T]) where T: Debug {
133 // details elided
134 }
135
136 foo(&[1, 2]);
137 ```
138
139 will instantiate type parameter `T` with `i32`.
140
141 The type parameters can also be explicitly supplied in a trailing [path]
142 component after the function name. This might be necessary if there is not
143 sufficient context to determine the type parameters. For example,
144 `mem::size_of::<u32>() == 4`.
145
146 ## Extern function qualifier
147
148 The `extern` function qualifier allows providing function _definitions_ that can
149 be called with a particular ABI:
150
151 <!-- ignore: fake ABI -->
152 ```rust,ignore
153 extern "ABI" fn foo() { /* ... */ }
154 ```
155
156 These are often used in combination with [external block] items which provide
157 function _declarations_ that can be used to call functions without providing
158 their _definition_:
159
160 <!-- ignore: fake ABI -->
161 ```rust,ignore
162 extern "ABI" {
163 fn foo(); /* no body */
164 }
165 unsafe { foo() }
166 ```
167
168 When `"extern" Abi?*` is omitted from `FunctionQualifiers` in function items,
169 the ABI `"Rust"` is assigned. For example:
170
171 ```rust
172 fn foo() {}
173 ```
174
175 is equivalent to:
176
177 ```rust
178 extern "Rust" fn foo() {}
179 ```
180
181 Functions in Rust can be called by foreign code, and using an ABI that
182 differs from Rust allows, for example, to provide functions that can be
183 called from other programming languages like C:
184
185 ```rust
186 // Declares a function with the "C" ABI
187 extern "C" fn new_i32() -> i32 { 0 }
188
189 // Declares a function with the "stdcall" ABI
190 # #[cfg(target_arch = "x86_64")]
191 extern "stdcall" fn new_i32_stdcall() -> i32 { 0 }
192 ```
193
194 Just as with [external block], when the `extern` keyword is used and the `"ABI`
195 is omitted, the ABI used defaults to `"C"`. That is, this:
196
197 ```rust
198 extern fn new_i32() -> i32 { 0 }
199 let fptr: extern fn() -> i32 = new_i32;
200 ```
201
202 is equivalent to:
203
204 ```rust
205 extern "C" fn new_i32() -> i32 { 0 }
206 let fptr: extern "C" fn() -> i32 = new_i32;
207 ```
208
209 Functions with an ABI that differs from `"Rust"` do not support unwinding in the
210 exact same way that Rust does. Therefore, unwinding past the end of functions
211 with such ABIs causes the process to abort.
212
213 > **Note**: The LLVM backend of the `rustc` implementation
214 aborts the process by executing an illegal instruction.
215
216 ## Const functions
217
218 Functions qualified with the `const` keyword are [const functions], as are
219 [tuple struct] and [tuple variant] constructors. _Const functions_ can be
220 called from within [const contexts].
221
222 Const functions are not allowed to be [async](#async-functions), and cannot
223 use the [`extern` function qualifier](#extern-function-qualifier).
224
225 ## Async functions
226
227 Functions may be qualified as async, and this can also be combined with the
228 `unsafe` qualifier:
229
230 ```rust
231 async fn regular_example() { }
232 async unsafe fn unsafe_example() { }
233 ```
234
235 Async functions do no work when called: instead, they
236 capture their arguments into a future. When polled, that future will
237 execute the function's body.
238
239 An async function is roughly equivalent to a function
240 that returns [`impl Future`] and with an [`async move` block][async-blocks] as
241 its body:
242
243 ```rust
244 // Source
245 async fn example(x: &str) -> usize {
246 x.len()
247 }
248 ```
249
250 is roughly equivalent to:
251
252 ```rust
253 # use std::future::Future;
254 // Desugared
255 fn example<'a>(x: &'a str) -> impl Future<Output = usize> + 'a {
256 async move { x.len() }
257 }
258 ```
259
260 The actual desugaring is more complex:
261
262 - The return type in the desugaring is assumed to capture all lifetime
263 parameters from the `async fn` declaration. This can be seen in the
264 desugared example above, which explicitly outlives, and hence
265 captures, `'a`.
266 - The [`async move` block][async-blocks] in the body captures all function
267 parameters, including those that are unused or bound to a `_`
268 pattern. This ensures that function parameters are dropped in the
269 same order as they would be if the function were not async, except
270 that the drop occurs when the returned future has been fully
271 awaited.
272
273 For more information on the effect of async, see [`async` blocks][async-blocks].
274
275 [async-blocks]: ../expressions/block-expr.md#async-blocks
276 [`impl Future`]: ../types/impl-trait.md
277
278 > **Edition differences**: Async functions are only available beginning with
279 > Rust 2018.
280
281 ### Combining `async` and `unsafe`
282
283 It is legal to declare a function that is both async and unsafe. The
284 resulting function is unsafe to call and (like any async function)
285 returns a future. This future is just an ordinary future and thus an
286 `unsafe` context is not required to "await" it:
287
288 ```rust
289 // Returns a future that, when awaited, dereferences `x`.
290 //
291 // Soundness condition: `x` must be safe to dereference until
292 // the resulting future is complete.
293 async unsafe fn unsafe_example(x: *const i32) -> i32 {
294 *x
295 }
296
297 async fn safe_example() {
298 // An `unsafe` block is required to invoke the function initially:
299 let p = 22;
300 let future = unsafe { unsafe_example(&p) };
301
302 // But no `unsafe` block required here. This will
303 // read the value of `p`:
304 let q = future.await;
305 }
306 ```
307
308 Note that this behavior is a consequence of the desugaring to a
309 function that returns an `impl Future` -- in this case, the function
310 we desugar to is an `unsafe` function, but the return value remains
311 the same.
312
313 Unsafe is used on an async function in precisely the same way that it
314 is used on other functions: it indicates that the function imposes
315 some additional obligations on its caller to ensure soundness. As in any
316 other unsafe function, these conditions may extend beyond the initial
317 call itself -- in the snippet above, for example, the `unsafe_example`
318 function took a pointer `x` as argument, and then (when awaited)
319 dereferenced that pointer. This implies that `x` would have to be
320 valid until the future is finished executing, and it is the caller's
321 responsibility to ensure that.
322
323 ## Attributes on functions
324
325 [Outer attributes][attributes] are allowed on functions. [Inner
326 attributes][attributes] are allowed directly after the `{` inside its [block].
327
328 This example shows an inner attribute on a function. The function is documented
329 with just the word "Example".
330
331 ```rust
332 fn documented() {
333 #![doc = "Example"]
334 }
335 ```
336
337 > Note: Except for lints, it is idiomatic to only use outer attributes on
338 > function items.
339
340 The attributes that have meaning on a function are [`cfg`], [`cfg_attr`], [`deprecated`],
341 [`doc`], [`export_name`], [`link_section`], [`no_mangle`], [the lint check
342 attributes], [`must_use`], [the procedural macro attributes], [the testing
343 attributes], and [the optimization hint attributes]. Functions also accept
344 attributes macros.
345
346 ## Attributes on function parameters
347
348 [Outer attributes][attributes] are allowed on function parameters and the
349 permitted [built-in attributes] are restricted to `cfg`, `cfg_attr`, `allow`,
350 `warn`, `deny`, and `forbid`.
351
352 ```rust
353 fn len(
354 #[cfg(windows)] slice: &[u16],
355 #[cfg(not(windows))] slice: &[u8],
356 ) -> usize {
357 slice.len()
358 }
359 ```
360
361 Inert helper attributes used by procedural macro attributes applied to items are also
362 allowed but be careful to not include these inert attributes in your final `TokenStream`.
363
364 For example, the following code defines an inert `some_inert_attribute` attribute that
365 is not formally defined anywhere and the `some_proc_macro_attribute` procedural macro is
366 responsible for detecting its presence and removing it from the output token stream.
367
368 <!-- ignore: requires proc macro -->
369 ```rust,ignore
370 #[some_proc_macro_attribute]
371 fn foo_oof(#[some_inert_attribute] arg: u8) {
372 }
373 ```
374
375 [IDENTIFIER]: ../identifiers.md
376 [RAW_STRING_LITERAL]: ../tokens.md#raw-string-literals
377 [STRING_LITERAL]: ../tokens.md#string-literals
378 [_BlockExpression_]: ../expressions/block-expr.md
379 [_GenericParams_]: generics.md
380 [_Lifetime_]: ../trait-bounds.md
381 [_PatternNoTopAlt_]: ../patterns.md
382 [_Type_]: ../types.md#type-expressions
383 [_WhereClause_]: generics.md#where-clauses
384 [_OuterAttribute_]: ../attributes.md
385 [const contexts]: ../const_eval.md#const-context
386 [const functions]: ../const_eval.md#const-functions
387 [tuple struct]: structs.md
388 [tuple variant]: enumerations.md
389 [external block]: external-blocks.md
390 [path]: ../paths.md
391 [block]: ../expressions/block-expr.md
392 [variables]: ../variables.md
393 [type]: ../types.md#type-expressions
394 [*function item type*]: ../types/function-item.md
395 [Trait]: traits.md
396 [attributes]: ../attributes.md
397 [`cfg`]: ../conditional-compilation.md#the-cfg-attribute
398 [`cfg_attr`]: ../conditional-compilation.md#the-cfg_attr-attribute
399 [the lint check attributes]: ../attributes/diagnostics.md#lint-check-attributes
400 [the procedural macro attributes]: ../procedural-macros.md
401 [the testing attributes]: ../attributes/testing.md
402 [the optimization hint attributes]: ../attributes/codegen.md#optimization-hints
403 [`deprecated`]: ../attributes/diagnostics.md#the-deprecated-attribute
404 [`doc`]: ../../rustdoc/the-doc-attribute.html
405 [`must_use`]: ../attributes/diagnostics.md#the-must_use-attribute
406 [patterns]: ../patterns.md
407 [`export_name`]: ../abi.md#the-export_name-attribute
408 [`link_section`]: ../abi.md#the-link_section-attribute
409 [`no_mangle`]: ../abi.md#the-no_mangle-attribute
410 [built-in attributes]: ../attributes.html#built-in-attributes-index
411 [trait item]: traits.md
412 [method]: associated-items.md#methods
413 [associated function]: associated-items.md#associated-functions-and-methods
414 [implementation]: implementations.md
415 [variadic function]: external-blocks.md#variadic-functions