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