3 > **<sup>Syntax</sup>**\
5 > _FunctionQualifiers_ `fn` [IDENTIFIER] [_Generics_]<sup>?</sup>\
6 > `(` _FunctionParameters_<sup>?</sup> `)`\
7 > _FunctionReturnType_<sup>?</sup> [_WhereClause_]<sup>?</sup>\
8 > [_BlockExpression_]
10 > _FunctionQualifiers_ :\
11 > _AsyncConstQualifiers_<sup>?</sup> `unsafe`<sup>?</sup> (`extern` _Abi_<sup>?</sup>)<sup>?</sup>
13 > _AsyncConstQualifiers_ :\
14 > `async` | `const`
17 > [STRING_LITERAL] | [RAW_STRING_LITERAL]
19 > _FunctionParameters_ :\
20 > _FunctionParam_ (`,` _FunctionParam_)<sup>\*</sup> `,`<sup>?</sup>
23 > [_OuterAttribute_]<sup>\*</sup> [_Pattern_] `:` [_Type_]
25 > _FunctionReturnType_ :\
26 > `->` [_Type_]
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
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.
39 For example, this is a simple function:
41 fn answer_to_life_the_universe_and_everything() -> i32 {
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:
50 fn first((value, _): (i32, i32)) -> i32 { value }
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.
59 For example, the function above behaves as if it was written as:
61 <!-- ignore: example expansion -->
63 // argument_0 is the actual first argument passed from the caller
64 let (value, _) = argument_0;
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.
77 // foo is generic over A and B
79 fn foo<A, B>(x: A, y: B) {
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:
89 # use std::fmt::Debug;
90 fn foo<T>(x: T) where T: Debug {
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:
100 fn foo<T>(x: &[T]) where T: Debug {
107 will instantiate type parameter `T` with `i32`.
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`.
114 ## Extern function qualifier
116 The `extern` function qualifier allows providing function _definitions_ that can
117 be called with a particular ABI:
119 +<!-- ignore: fake ABI -->
121 extern "ABI" fn foo() { /* ... */ }
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
128 +<!-- ignore: fake ABI -->
131 fn foo(); /* no body */
136 When `"extern" Abi?*` is omitted from `FunctionQualifiers` in function items,
137 the ABI `"Rust"` is assigned. For example:
146 extern "Rust" fn foo() {}
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:
154 // Declares a function with the "C" ABI
155 extern "C" fn new_i32() -> i32 { 0 }
157 // Declares a function with the "stdcall" ABI
158 # #[cfg(target_arch = "x86_64")]
159 extern "stdcall" fn new_i32_stdcall() -> i32 { 0 }
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:
166 extern fn new_i32() -> i32 { 0 }
167 let fptr: extern fn() -> i32 = new_i32;
173 extern "C" fn new_i32() -> i32 { 0 }
174 let fptr: extern "C" fn() -> i32 = new_i32;
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.
181 > **Note**: The LLVM backend of the `rustc` implementation
182 aborts the process by executing an illegal instruction.
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.
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.
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.
207 Exhaustive list of permitted structures in const functions:
209 > **Note**: this list is more restrictive than what you can write in
212 * Type parameters where the parameters only have any [trait bounds]
213 of the following kind:
215 * `Sized` or [`?Sized`]
217 This means that `<T: 'a + ?Sized>`, `<T: 'b + Sized>`, and `<T>`
220 This rule also applies to type parameters of impl blocks that
221 contain const methods.
223 This does not apply to tuple struct and tuple variant constructors.
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
241 Functions may be qualified as async, and this can also be combined with the
245 async fn regular_example() { }
246 async unsafe fn unsafe_example() { }
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.
253 An async function is roughly equivalent to a function
254 that returns [`impl Future`] and with an [`async move` block][async-blocks] as
259 async fn example(x: &str) -> usize {
264 is roughly equivalent to:
267 # use std::future::Future;
269 fn example<'a>(x: &'a str) -> impl Future<Output = usize> + 'a {
270 async move { x.len() }
274 The actual desugaring is more complex:
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
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
287 For more information on the effect of async, see [`async` blocks][async-blocks].
289 [async-blocks]: ../expressions/block-expr.md#async-blocks
290 [`impl Future`]: ../types/impl-trait.md
292 > **Edition differences**: Async functions are only available beginning with
295 ### Combining `async` and `unsafe`
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:
303 // Returns a future that, when awaited, dereferences `x`.
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 {
311 async fn safe_example() {
312 // An `unsafe` block is required to invoke the function initially:
314 let future = unsafe { unsafe_example(&p) };
316 // But no `unsafe` block required here. This will
317 // read the value of `p`:
318 let q = future.await;
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
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.
337 ## Attributes on functions
339 [Outer attributes][attributes] are allowed on functions. [Inner
340 attributes][attributes] are allowed directly after the `{` inside its [block].
342 This example shows an inner attribute on a function. The function will only be
343 available while running tests.
351 > Note: Except for lints, it is idiomatic to only use outer attributes on
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
360 ## Attributes on function parameters
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`.
368 #[cfg(windows)] slice: &[u16],
369 #[cfg(not(windows))] slice: &[u8],
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`.
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.
382 <!-- ignore: requires proc macro -->
384 #[some_proc_macro_attribute]
385 fn foo_oof(#[some_inert_attribute] arg: u8) {
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
403 [block]: ../expressions/block-expr.md
404 [variables]: ../variables.md
405 [type]: ../types.md#type-expressions
406 [*function item type*]: ../types/function-item.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