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