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:
62 // argument_0 is the actual first argument passed from the caller
63 let (value, _) = argument_0;
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.
76 // foo is generic over A and B
78 fn foo<A, B>(x: A, y: B) {
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:
88 # use std::fmt::Debug;
89 fn foo<T>(x: T) where T: Debug {
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:
99 fn foo<T>(x: &[T]) where T: Debug {
106 will instantiate type parameter `T` with `i32`.
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`.
113 ## Extern function qualifier
115 The `extern` function qualifier allows providing function _definitions_ that can
116 be called with a particular ABI:
119 extern "ABI" fn foo() { ... }
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
128 fn foo(); /* no body */
133 When `"extern" Abi?*` is omitted from `FunctionQualifiers` in function items,
134 the ABI `"Rust"` is assigned. For example:
143 extern "Rust" fn foo() {}
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:
151 // Declares a function with the "C" ABI
152 extern "C" fn new_i32() -> i32 { 0 }
154 // Declares a function with the "stdcall" ABI
155 # #[cfg(target_arch = "x86_64")]
156 extern "stdcall" fn new_i32_stdcall() -> i32 { 0 }
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:
163 extern fn new_i32() -> i32 { 0 }
164 let fptr: extern fn() -> i32 = new_i32;
170 extern "C" fn new_i32() -> i32 { 0 }
171 let fptr: extern "C" fn() -> i32 = new_i32;
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.
178 > **Note**: The LLVM backend of the `rustc` implementation
179 aborts the process by executing an illegal instruction.
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.
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.
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.
204 Exhaustive list of permitted structures in const functions:
206 > **Note**: this list is more restrictive than what you can write in
209 * Type parameters where the parameters only have any [trait bounds]
210 of the following kind:
212 * `Sized` or [`?Sized`]
214 This means that `<T: 'a + ?Sized>`, `<T: 'b + Sized>`, and `<T>`
217 This rule also applies to type parameters of impl blocks that
218 contain const methods.
220 This does not apply to tuple struct and tuple variant constructors.
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
238 Functions may be qualified as async, and this can also be combined with the
242 async fn regular_example() { }
243 async unsafe fn unsafe_example() { }
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.
250 An async function is roughly equivalent to a function
251 that returns [`impl Future`] and with an [`async move` block][async-blocks] as
256 async fn example(x: &str) -> usize {
261 is roughly equivalent to:
264 # use std::future::Future;
266 fn example<'a>(x: &'a str) -> impl Future<Output = usize> + 'a {
267 async move { x.len() }
271 The actual desugaring is more complex:
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
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
284 For more information on the effect of async, see [`async` blocks][async-blocks].
286 [async-blocks]: ../expressions/block-expr.md#async-blocks
287 [`impl Future`]: ../types/impl-trait.md
289 > **Edition differences**: Async functions are only available beginning with
292 ### Combining `async` and `unsafe`
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:
300 // Returns a future that, when awaited, dereferences `x`.
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 {
308 async fn safe_example() {
309 // An `unsafe` block is required to invoke the function initially:
311 let future = unsafe { unsafe_example(&p) };
313 // But no `unsafe` block required here. This will
314 // read the value of `p`:
315 let q = future.await;
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
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.
334 ## Attributes on functions
336 [Outer attributes][attributes] are allowed on functions. [Inner
337 attributes][attributes] are allowed directly after the `{` inside its [block].
339 This example shows an inner attribute on a function. The function will only be
340 available while running tests.
348 > Note: Except for lints, it is idiomatic to only use outer attributes on
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
357 ## Attributes on function parameters
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`.
365 #[cfg(windows)] slice: &[u16],
366 #[cfg(not(windows))] slice: &[u8],
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`.
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.
380 #[some_proc_macro_attribute]
381 fn foo_oof(#[some_inert_attribute] arg: u8) {
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
399 [block]: ../expressions/block-expr.md
400 [variables]: ../variables.md
401 [type]: ../types.md#type-expressions
402 [*function item type*]: ../types/function-item.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