Functions
Syntax
Function →
FunctionQualifiers fn IDENTIFIER GenericParams?
( FunctionParameters? )
FunctionReturnType? WhereClause?
( BlockExpression | ; )
FunctionQualifiers → const? async?1 ItemSafety?2 ( extern Abi? )?
ItemSafety → safe3 | unsafe
Abi → STRING_LITERAL | RAW_STRING_LITERAL
FunctionParameters →
SelfParam ,?
| ( SelfParam , )? FunctionParam ( , FunctionParam )* ,?
SelfParam → OuterAttribute* ( ShorthandSelf | TypedSelf )
ShorthandSelf → ( & | & Lifetime )? mut? self
FunctionParam → OuterAttribute* ( FunctionParamPattern | ... | Type4 )
FunctionParamPattern → PatternNoTopAlt : ( Type | ... )
FunctionReturnType → -> Type
A function consists of a block (that’s the body of the function), along with a name, a set of parameters, and an output type. Other than a name, all these are optional.
Functions are declared with the keyword fn which defines the given name in the value namespace of the module or block where it is located.
Functions may declare a set of input variables as parameters, through which the caller passes arguments into the function, and the output type of the value the function will return to its caller on completion.
If the output type is not explicitly stated, it is the unit type.
When referred to, a function yields a first-class value of the corresponding zero-sized function item type, which when called evaluates to a direct call to the function.
For example, this is a simple function:
#![allow(unused)]
fn main() {
fn answer_to_life_the_universe_and_everything() -> i32 {
return 42;
}
}
The safe function is semantically only allowed when used in an extern block.
Function parameters
Function parameters are irrefutable patterns, so any pattern that is valid in an else-less let binding is also valid as a parameter:
#![allow(unused)]
fn main() {
fn first((value, _): (i32, i32)) -> i32 { value }
}
If the first parameter is a SelfParam, this indicates that the function is a method.
Functions with a self parameter may only appear as an associated function in a trait or implementation.
A parameter with the ... token indicates a C-variadic function and may only be used as the last parameter. In a function declaration in an extern block, the C-variadic parameter may have a pattern, such as ap: ..., and in a C-variadic function definition or C-variadic associated function declaration in a trait definition, the pattern is mandatory.
#![allow(unused)]
fn main() {
unsafe extern "C" {
unsafe fn f1(...);
unsafe fn f2(ap: ...);
}
unsafe extern "C" fn f3(ap: ...) {}
trait Tr {
unsafe extern "C" fn f4(ap: ...);
}
}
#![allow(unused)]
fn main() {
unsafe extern "C" fn f(...) {} // ERROR: Missing pattern.
}
#![allow(unused)]
fn main() {
trait Tr {
unsafe extern "C" fn f(...); // ERROR: Missing pattern.
}
}
Function body
The body block of a function is conceptually wrapped in another block that first binds the argument patterns and then returns the value of the function’s body. This means that the tail expression of the block, if evaluated, ends up being returned to the caller. As usual, an explicit return expression within the body of the function will short-cut that implicit return, if reached.
For example, the function above behaves as if it was written as:
// argument_0 is the actual first argument passed from the caller
let (value, _) = argument_0;
return {
value
};
Functions without a body block are terminated with a semicolon. This form may only appear in a trait or external block.
Generic functions
A generic function allows one or more parameterized types to appear in its signature. Each type parameter must be explicitly declared in an angle-bracket-enclosed and comma-separated list, following the function name.
#![allow(unused)]
fn main() {
// foo is generic over A and B
fn foo<A, B>(x: A, y: B) {
}
}
Inside the function signature and body, the name of the type parameter can be used as a type name.
Trait bounds can be specified for type parameters to allow methods from that trait to be called on values of that type. This is specified using the where syntax:
#![allow(unused)]
fn main() {
use std::fmt::Debug;
fn foo<T>(x: T) where T: Debug {
}
}
When a generic function is referenced, its type is instantiated based on the context of the reference. For example, calling the foo function here:
#![allow(unused)]
fn main() {
use std::fmt::Debug;
fn foo<T>(x: &[T]) where T: Debug {
// details elided
}
foo(&[1, 2]);
}
will instantiate type parameter T with i32.
The type parameters can also be explicitly supplied in a trailing path component after the function name. This might be necessary if there is not sufficient context to determine the type parameters. For example, mem::size_of::<u32>() == 4.
Extern function qualifier
The extern function qualifier allows providing function definitions that can be called with a particular ABI:
extern "ABI" fn foo() { /* ... */ }
These are often used in combination with external block items which provide function declarations that can be used to call functions without providing their definition:
unsafe extern "ABI" {
unsafe fn foo(); /* no body */
safe fn bar(); /* no body */
}
unsafe { foo() };
bar();
When "extern" Abi?* is omitted from FunctionQualifiers in function items, the ABI "Rust" is assigned. For example:
#![allow(unused)]
fn main() {
fn foo() {}
}
is equivalent to:
#![allow(unused)]
fn main() {
extern "Rust" fn foo() {}
}
Functions can be called by foreign code, and using an ABI that differs from Rust allows, for example, to provide functions that can be called from other programming languages like C:
#![allow(unused)]
fn main() {
// Declares a function with the "C" ABI
extern "C" fn new_i32() -> i32 { 0 }
// Declares a function with the "stdcall" ABI
#[cfg(any(windows, target_arch = "x86"))]
extern "stdcall" fn new_i32_stdcall() -> i32 { 0 }
}
Just as with external block, when the extern keyword is used and the "ABI" is omitted, the ABI used defaults to "C". That is, this:
#![allow(unused)]
fn main() {
extern fn new_i32() -> i32 { 0 }
let fptr: extern fn() -> i32 = new_i32;
}
is equivalent to:
#![allow(unused)]
fn main() {
extern "C" fn new_i32() -> i32 { 0 }
let fptr: extern "C" fn() -> i32 = new_i32;
}
Unwinding
Most ABI strings come in two variants, one with an -unwind suffix and one without. The Rust ABI always permits unwinding, so there is no Rust-unwind ABI. The choice of ABI, together with the runtime panic handler, determines the behavior when unwinding out of a function.
The table below indicates the behavior of an unwinding operation reaching each type of ABI boundary (function declaration or definition using the corresponding ABI string). Note that the Rust runtime is not affected by, and cannot have an effect on, any unwinding that occurs entirely within another language’s runtime, that is, unwinds that are thrown and caught without reaching a Rust ABI boundary.
The panic-unwind column refers to panicking via the panic! macro and similar standard library mechanisms, as well as to any other Rust operations that cause a panic, such as out-of-bounds array indexing or integer overflow.
The “unwinding” ABI category refers to "Rust" (the implicit ABI of Rust functions not marked extern), "C-unwind", and any other ABI with -unwind in its name. The “non-unwinding” ABI category refers to all other ABI strings, including "C" and "stdcall".
Native unwinding is defined per-target. On targets that support throwing and catching C++ exceptions, it refers to the mechanism used to implement this feature. Some platforms implement a form of unwinding referred to as “forced unwinding”; longjmp on Windows and pthread_exit in glibc are implemented this way. Forced unwinding is explicitly excluded from the “Native unwind” column in the table.
| panic runtime | ABI | panic-unwind | Native unwind (unforced) |
|---|---|---|---|
panic=unwind | unwinding | unwind | unwind |
panic=unwind | non-unwinding | abort (see notes below) | undefined behavior |
panic=abort | unwinding | panic aborts without unwinding | abort |
panic=abort | non-unwinding | panic aborts without unwinding | undefined behavior |
With panic=unwind, when a panic is turned into an abort by a non-unwinding ABI boundary, either no destructors (Drop calls) will run, or all destructors up until the ABI boundary will run. It is unspecified which of those two behaviors will happen.
For other considerations and limitations regarding unwinding across FFI boundaries, see the relevant section in the Panic documentation.
Const functions
See const functions for the definition of const functions.
Async functions
Functions may be qualified as async, and this can also be combined with the unsafe qualifier:
#![allow(unused)]
fn main() {
async fn regular_example() { }
async unsafe fn unsafe_example() { }
}
Async functions do no work when called: instead, they capture their arguments into a future. When polled, that future will execute the function’s body.
An async function is roughly equivalent to a function that returns impl Future and with an async move block as its body:
#![allow(unused)]
fn main() {
// Source
async fn example(x: &str) -> usize {
x.len()
}
}
is roughly equivalent to:
#![allow(unused)]
fn main() {
use std::future::Future;
// Desugared
fn example<'a>(x: &'a str) -> impl Future<Output = usize> + 'a {
async move { x.len() }
}
}
The actual desugaring is more complex:
- The return type in the desugaring is assumed to capture all lifetime parameters from the
async fndeclaration. This can be seen in the desugared example above, which explicitly outlives, and hence captures,'a.
- The
async moveblock in the body captures all function parameters, including those that are unused or bound to a_pattern. This ensures that function parameters are dropped in the same order as they would be if the function were not async, except that the drop occurs when the returned future has been fully awaited.
For more information on the effect of async, see async blocks.
2018 Edition differences
Async functions are only available beginning with Rust 2018.
Combining async and unsafe
It is legal to declare a function that is both async and unsafe. The resulting function is unsafe to call and (like any async function) returns a future. This future is just an ordinary future and thus an unsafe context is not required to “await” it:
#![allow(unused)]
fn main() {
// Returns a future that, when awaited, dereferences `x`.
//
// Soundness condition: `x` must be safe to dereference until
// the resulting future is complete.
async unsafe fn unsafe_example(x: *const i32) -> i32 {
*x
}
async fn safe_example() {
// An `unsafe` block is required to invoke the function initially:
let p = 22;
let future = unsafe { unsafe_example(&p) };
// But no `unsafe` block required here. This will
// read the value of `p`:
let q = future.await;
}
}
Note that this behavior is a consequence of the desugaring to a function that returns an impl Future – in this case, the function we desugar to is an unsafe function, but the return value remains the same.
Unsafe is used on an async function in precisely the same way that it is used on other functions: it indicates that the function imposes some additional obligations on its caller to ensure soundness. As in any other unsafe function, these conditions may extend beyond the initial call itself – in the snippet above, for example, the unsafe_example function took a pointer x as argument, and then (when awaited) dereferenced that pointer. This implies that x would have to be valid until the future is finished executing, and it is the caller’s responsibility to ensure that.
C-variadic functions
A C-variadic function accepts a variable argument list pat: ... as its final parameter.
#![allow(unused)]
fn main() {
unsafe extern "C" fn f(mut ap: ...) -> f64 {
unsafe { ap.next_arg::<f64>() }
}
}
#![allow(unused)]
fn main() {
unsafe extern "C" fn f(ap: ..., _: ()) {} // ERROR: `...` must be last.
}
This parameter stands in for an arbitrary number of arguments that may be passed by the caller.
The type of pat in the function body is VaList<'_>.
#![allow(unused)]
fn main() {
use core::ffi::VaList;
unsafe extern "C" fn f(ap: ...) {
let _: VaList<'_> = ap;
}
}
A C-variadic function definition is implicitly generic over the lifetime of its variadic parameter, as if the parameter had type VaList<'x> for a fresh, unnameable lifetime 'x. Because the function must be valid for any such lifetime, the VaList cannot be proved to outlive any caller-provided lifetime (and so cannot escape the call) and no caller-provided lifetime can be proved to outlive it.
#![allow(unused)]
fn main() {
use core::ffi::VaList;
fn b_outlives_a<'a, 'b: 'a>(_: &mut VaList<'a>, _: &mut &'b mut u8) {}
unsafe extern "C" fn f(mut r: &mut u8, mut ap: ...) {
b_outlives_a(&mut ap, &mut r); // ERROR: May not live long enough.
}
}
#![allow(unused)]
fn main() {
use core::ffi::VaList;
fn a_outlives_b<'a: 'b, 'b>(_: &mut VaList<'a>, _: &mut &'b mut u8) {}
unsafe extern "C" fn f(mut r: &mut u8, mut ap: ...) {
a_outlives_b(&mut ap, &mut r); // ERROR: May not live long enough.
}
}
Note
This is different than if the data were a stack variable: any caller-provided lifetime can be proved to outlive a borrow of a callee stack variable.
#![allow(unused)] fn main() { struct MockVaList<'data>(&'data u8); fn b_outlives_a<'a, 'b: 'a>(_: &mut MockVaList<'a>, _: &mut &'b mut u8) {} unsafe extern "C" fn f(mut r: &mut u8) { let data = 0; let mut ap = MockVaList(&data); b_outlives_a(&mut ap, &mut r); // OK. } }
A C-variadic function definition is roughly equivalent to a function operating on a VaList.
#![allow(unused)]
fn main() {
unsafe extern "C" fn f(mut ap: ...) -> i32 {
unsafe { ap.next_arg::<i32>() }
}
}
Roughly desugars to:
#![allow(unused)]
fn main() {
#![ feature(core_intrinsics) ]
#![allow(internal_features)]
use core::ffi::VaList;
use core::mem::MaybeUninit;
use core::intrinsics::{va_arg, va_end};
// `va_start` is magic and has no intrinsic.
fn va_start(ap: *mut VaList<'_>) { /* magic */ }
unsafe extern "C" fn f() -> i32 {
unsafe {
let mut ap: MaybeUninit<VaList<'_>> = MaybeUninit::uninit();
va_start(ap.as_mut_ptr());
let mut ap = ap.assume_init();
let x = va_arg::<i32>(&mut ap);
va_end(&mut ap);
x
}
}
}
Note
In an actual C-variadic function definition, the lifetime in
VaList<'_>is different from what this code would suggest. See items.fn.c-variadic.lifetime.
Calling VaList::next_arg to read an argument of type T is only safe if all of the following conditions are satisfied:
- There is another C-variadic argument to read.
- The actual type of the argument
Uis compatible withT(as defined below). - If
UandTare both integer types, then the value passed by the caller must be representable in both types.
Types T and U are compatible when one of the following is true:
TandUare the same type (up to free lifetimes).TandUare integer types of the same size.TandUare both pointers and their target types are compatible.Tis a pointer toc_voidandUis a pointer toi8oru8, or vice versa.
Examples of compatible types are:
u32andi32— but UB may still occur if the value is not representable in the target type.u64andusize— on a 64-bit platform.*const &'a u32and*mut &'static u32— these types are equal up to free lifetimes.
Examples of incompatible types are:
usizeand*const _— pointers and integers are not compatible.*const fn(&'static ())and*const for<'a> fn(&'a ())— these types are not equal up to free lifetimes.
VaList is ABI compatible with the C va_list type.
#![allow(unused)]
fn main() {
use core::ffi::{c_char, c_int, VaList};
unsafe extern "C" {
// The C `vprintf` function is:
//
// int vprintf(const char *format, va_list ap);
//
unsafe fn vprintf(fmt: *const c_char, ap: VaList<'_>) -> c_int;
}
unsafe extern "C" fn print(fmt: *const c_char, ap: ...) -> c_int {
// The `VaList` is passed directly to the C function.
unsafe { vprintf(fmt, ap) }
}
}
Only extern "C" and extern "C-unwind" function definitions can accept a variable argument list.
#![allow(unused)]
fn main() {
unsafe fn f(ap: ...) {} // ERROR: Not supported.
}
#![allow(unused)]
fn main() {
unsafe extern "sysv64" fn f(ap: ...) {} // ERROR: Not supported.
}
When a variable argument list is used in the signature:
- Function definitions must be
unsafe. - Function declarations within trait definitions must be
unsafe. - Function declarations in
externblocks may besafe.
#![allow(unused)]
fn main() {
extern "C" fn f(ap: ...) {} // ERROR: Must be `unsafe`.
}
#![allow(unused)]
fn main() {
trait Tr {
extern "C" fn f(ap: ...); // ERROR: Must be `unsafe`.
}
}
#![allow(unused)]
fn main() {
unsafe extern "C" {
safe fn f(ap: ...); // OK.
}
}
Note
For
safefunction declarations in anexternblock, see the warning in items.extern.variadic.
A C-variadic function cannot be async.
#![allow(unused)]
fn main() {
async unsafe extern "C" fn f(ap: ...) {} // ERROR: Cannot be `async`.
}
A C-variadic function cannot be const.
#![allow(unused)]
fn main() {
const unsafe extern "C" fn f(ap: ...) {} // ERROR: Cannot be `const`.
}
Support for C-variadic function definitions is stable on the following target architectures:
- x86 and x86-64
- ARM
- AArch64 and Arm64EC
- RISC-V 32-bit and 64-bit (except when using the ilp32e ABI)
- LoongArch 32-bit and 64-bit
- s390x
- PowerPC and PowerPC64
- AMDGPU and NVPTX
- Wasm32 and Wasm64
- C-SKY
- Xtensa
- Hexagon
- SPARC64
- MIPS
Note
Some target architectures (e.g., BPF) do not support C-variadic function definitions. The compiler will emit an error if such a definition is used on an unsupported target.
Attributes on functions
Outer attributes are allowed on functions. Inner attributes are allowed directly after the { inside its body block.
This example shows an inner attribute on a function. The function is documented with just the word “Example”.
#![allow(unused)]
fn main() {
fn documented() {
#![doc = "Example"]
}
}
Note
Except for lints, it is idiomatic to only use outer attributes on function items.
The attributes that have meaning on a function are:
cfg_attrcfgcolddeprecateddocexport_nameinlinelink_sectionmust_useno_mangle- Lint check attributes
- Procedural macro attributes
- Testing attributes
Attributes on function parameters
Outer attributes are allowed on function parameters and the permitted built-in attributes are restricted to cfg, cfg_attr, allow, warn, deny, and forbid.
#![allow(unused)]
fn main() {
fn len(
#[cfg(windows)] slice: &[u16],
#[cfg(not(windows))] slice: &[u8],
) -> usize {
slice.len()
}
}
Inert helper attributes used by procedural macro attributes applied to items are also allowed but be careful to not include these inert attributes in your final TokenStream.
For example, the following code defines an inert some_inert_attribute attribute that is not formally defined anywhere and the some_proc_macro_attribute procedural macro is responsible for detecting its presence and removing it from the output token stream.
#[some_proc_macro_attribute]
fn foo_oof(#[some_inert_attribute] arg: u8) {
}
-
The
asyncqualifier is not allowed in the 2015 edition. ↩ -
Relevant to editions earlier than Rust 2024: Within
externblocks, thesafeorunsafefunction qualifier is only allowed when theexternis qualified asunsafe. ↩ -
The
safefunction qualifier is only allowed semantically withinexternblocks. ↩ -
Function parameters with only a type are only allowed in an associated function of a trait item in the 2015 edition. ↩