3 > **<sup>Syntax</sup>**\
5 > _FunctionQualifiers_ `fn` [IDENTIFIER] [_GenericParams_]<sup>?</sup>\
6 > `(` _FunctionParameters_<sup>?</sup> `)`\
7 > _FunctionReturnType_<sup>?</sup> [_WhereClause_]<sup>?</sup>\
8 > ( [_BlockExpression_] | `;` )
10 > _FunctionQualifiers_ :\
11 > `const`<sup>?</sup> `async`[^async-edition]<sup>?</sup> `unsafe`<sup>?</sup> (`extern` _Abi_<sup>?</sup>)<sup>?</sup>
14 > [STRING_LITERAL] | [RAW_STRING_LITERAL]
16 > _FunctionParameters_ :\
17 > _SelfParam_ `,`<sup>?</sup>\
18 > | (_SelfParam_ `,`)<sup>?</sup> _FunctionParam_ (`,` _FunctionParam_)<sup>\*</sup> `,`<sup>?</sup>
21 > [_OuterAttribute_]<sup>\*</sup> ( _ShorthandSelf_ | _TypedSelf_ )
24 > (`&` | `&` [_Lifetime_])<sup>?</sup> `mut`<sup>?</sup> `self`
27 > `mut`<sup>?</sup> `self` `:` [_Type_]
30 > [_OuterAttribute_]<sup>\*</sup> (
31 > _FunctionParamPattern_ | `...` | [_Type_] [^fn-param-2015]
34 > _FunctionParamPattern_ :\
35 > [_PatternNoTopAlt_] `:` ( [_Type_] | `...` )
37 > _FunctionReturnType_ :\
38 > `->` [_Type_]
40 > [^async-edition]: The `async` qualifier is not allowed in the 2015 edition.
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.
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
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.
56 For example, this is a simple function:
58 fn answer_to_life_the_universe_and_everything() -> i32 {
63 ## Function parameters
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:
69 fn first((value, _): (i32, i32)) -> i32 { value }
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].
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: ...`.
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.
88 For example, the function above behaves as if it was written as:
90 <!-- ignore: example expansion -->
92 // argument_0 is the actual first argument passed from the caller
93 let (value, _) = argument_0;
99 Functions without a body block are terminated with a semicolon. This form
100 may only appear in a [trait] or [external block].
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.
109 // foo is generic over A and B
111 fn foo<A, B>(x: A, y: B) {
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:
121 # use std::fmt::Debug;
122 fn foo<T>(x: T) where T: Debug {
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:
132 fn foo<T>(x: &[T]) where T: Debug {
139 will instantiate type parameter `T` with `i32`.
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`.
146 ## Extern function qualifier
148 The `extern` function qualifier allows providing function _definitions_ that can
149 be called with a particular ABI:
151 <!-- ignore: fake ABI -->
153 extern "ABI" fn foo() { /* ... */ }
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
160 <!-- ignore: fake ABI -->
163 fn foo(); /* no body */
168 When `"extern" Abi?*` is omitted from `FunctionQualifiers` in function items,
169 the ABI `"Rust"` is assigned. For example:
178 extern "Rust" fn foo() {}
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:
186 // Declares a function with the "C" ABI
187 extern "C" fn new_i32() -> i32 { 0 }
189 // Declares a function with the "stdcall" ABI
190 # #[cfg(target_arch = "x86_64")]
191 extern "stdcall" fn new_i32_stdcall() -> i32 { 0 }
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:
198 extern fn new_i32() -> i32 { 0 }
199 let fptr: extern fn() -> i32 = new_i32;
205 extern "C" fn new_i32() -> i32 { 0 }
206 let fptr: extern "C" fn() -> i32 = new_i32;
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.
213 > **Note**: The LLVM backend of the `rustc` implementation
214 aborts the process by executing an illegal instruction.
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].
222 Const functions are not allowed to be [async](#async-functions), and cannot
223 use the [`extern` function qualifier](#extern-function-qualifier).
227 Functions may be qualified as async, and this can also be combined with the
231 async fn regular_example() { }
232 async unsafe fn unsafe_example() { }
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.
239 An async function is roughly equivalent to a function
240 that returns [`impl Future`] and with an [`async move` block][async-blocks] as
245 async fn example(x: &str) -> usize {
250 is roughly equivalent to:
253 # use std::future::Future;
255 fn example<'a>(x: &'a str) -> impl Future<Output = usize> + 'a {
256 async move { x.len() }
260 The actual desugaring is more complex:
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
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
273 For more information on the effect of async, see [`async` blocks][async-blocks].
275 [async-blocks]: ../expressions/block-expr.md#async-blocks
276 [`impl Future`]: ../types/impl-trait.md
278 > **Edition differences**: Async functions are only available beginning with
281 ### Combining `async` and `unsafe`
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:
289 // Returns a future that, when awaited, dereferences `x`.
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 {
297 async fn safe_example() {
298 // An `unsafe` block is required to invoke the function initially:
300 let future = unsafe { unsafe_example(&p) };
302 // But no `unsafe` block required here. This will
303 // read the value of `p`:
304 let q = future.await;
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
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.
323 ## Attributes on functions
325 [Outer attributes][attributes] are allowed on functions. [Inner
326 attributes][attributes] are allowed directly after the `{` inside its [block].
328 This example shows an inner attribute on a function. The function is documented
329 with just the word "Example".
337 > Note: Except for lints, it is idiomatic to only use outer attributes on
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
346 ## Attributes on function parameters
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`.
354 #[cfg(windows)] slice: &[u16],
355 #[cfg(not(windows))] slice: &[u8],
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`.
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.
368 <!-- ignore: requires proc macro -->
370 #[some_proc_macro_attribute]
371 fn foo_oof(#[some_inert_attribute] arg: u8) {
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
391 [block]: ../expressions/block-expr.md
392 [variables]: ../variables.md
393 [type]: ../types.md#type-expressions
394 [*function item type*]: ../types/function-item.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