For now, this reference is a best-effort document. We strive for validity and completeness, but are not yet there. In the future, the docs and lang teams will work together to figure out how best to do this. Until then, this is a best-effort attempt. If you find something wrong or missing, file an issue or send in a pull request.

Function pointer types

Syntax
BareFunctionType :
   ForLifetimes? FunctionQualifiers fn
      ( FunctionParametersMaybeNamedVariadic? ) BareFunctionReturnType?

BareFunctionReturnType:
   -> TypeNoBounds

FunctionParametersMaybeNamedVariadic :
   MaybeNamedFunctionParameters | MaybeNamedFunctionParametersVariadic

MaybeNamedFunctionParameters :
   MaybeNamedParam ( , MaybeNamedParam )* ,?

MaybeNamedParam :
   ( ( IDENTIFIER | _ ) : )? Type

MaybeNamedFunctionParametersVariadic :
   ( MaybeNamedParam , )* MaybeNamedParam , ...

Function pointer types, written using the fn keyword, refer to a function whose identity is not necessarily known at compile-time. They can be created via a coercion from both function items and non-capturing closures.

The unsafe qualifier indicates that the type's value is an unsafe function, and the extern qualifier indicates it is an extern function.

Variadic parameters can only be specified with extern function types with the "C" or "cdecl" calling convention.

An example where Binop is defined as a function pointer type:


# #![allow(unused_variables)]
#fn main() {
fn add(x: i32, y: i32) -> i32 {
    x + y
}

let mut x = add(5,7);

type Binop = fn(i32, i32) -> i32;
let bo: Binop = add;
x = bo(5,7);
#}