Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Keywords and Statements

The fn keyword

Reference for Rust fn: defining functions, parameters and return types, generics, const and unsafe qualifiers, nested functions and the fn pointer type.

fn defines a function: a name, a typed parameter list, an optional return type after ->, and a block body. Parameter and return types must always be written out; Rust does not infer signatures, which keeps function boundaries clear for readers and for the compiler. A function without -> returns the unit type ().

fn also appears in types. fn(i32) -> i32 is the function pointer type, which any non-capturing function or closure can coerce to. It is different from the traits Fn, FnMut and FnOnce, which describe anything callable, including closures that capture variables.

Rust
fn add(a: i32, b: i32) -> i32 {
    a + b
}
let op: fn(i32, i32) -> i32 = add;

Try it

Rust Defining and calling functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust Function pointers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
[pub] [const] [async] [unsafe] [extern "ABI"] fn name<GENERICS>(params) -> ReturnType
where
    BOUNDS
{
    body
}

fn(ParamType, ...) -> ReturnType          // function pointer type
Part Description
name snake_case by convention.
params name: Type separated by commas. Patterns are allowed: (a, b): (i32, i32); mut x makes the parameter mutable inside. Methods start with self, &self or &mut self.
-> ReturnType Omitted for (). The value is the last expression of the body or a return.
Qualifiers const (usable in constant contexts), async (returns a future), unsafe (callers must uphold extra conditions), extern "C" (C calling convention).

Errors: calling with the wrong number of arguments is E0061; wrong argument or return types are E0308. There are no default arguments, no overloading by parameter list, and no named arguments.

Usage notes

  • Arguments are moved or copied. Passing a String moves it; pass &str or &String to borrow. Prefer &str and &[T] over owning types in parameters.
  • Order of definition does not matter for items: a function can call one defined further down the file.
  • Function items versus pointers. Each fn has its own zero-sized type; coercion to fn(...) pointer happens when types must be uniform, as in arrays and structs. Generic code with F: Fn(i32) -> i32 is usually faster because the call can be inlined.
  • Capturing closures cannot become fn pointers; they need generics, impl Fn, or Box<dyn Fn>.
  • Recursion is allowed; there is no guaranteed tail-call elimination, so very deep recursion can overflow the stack.
  • main is the entry point: fn main() or fn main() -> Result<(), E>.
  • Return impl Trait to hide a concrete type such as an iterator: fn evens() -> impl Iterator<Item = u32>.
  • Associated functions inside impl blocks without self are called as Type::name(); see impl.