Function pointer types
Syntax
BareFunctionType :
ForLifetimes? FunctionTypeQualifiersfn
(
FunctionParametersMaybeNamedVariadic?)
BareFunctionReturnType?FunctionTypeQualifiers:
unsafe
? (extern
Abi?)?BareFunctionReturnType:
->
TypeNoBoundsFunctionParametersMaybeNamedVariadic :
MaybeNamedFunctionParameters | MaybeNamedFunctionParametersVariadicMaybeNamedFunctionParameters :
MaybeNamedParam (,
MaybeNamedParam )*,
?MaybeNamedParam :
OuterAttribute* ( ( IDENTIFIER |_
):
)? TypeMaybeNamedFunctionParametersVariadic :
( MaybeNamedParam,
)* MaybeNamedParam,
OuterAttribute*...
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, non-async 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
these calling conventions:
C
cdecl
system
aapcs
sysv64
win64
efiapi
An example where Binop
is defined as a function pointer type:
#![allow(unused)] 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); }
Attributes on function pointer parameters
Attributes on function pointer parameters follow the same rules and restrictions as regular function parameters.