Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Core Traits

The Fn, FnMut and FnOnce traits

Reference for Rust Fn, FnMut and FnOnce: how closures capture variables, which trait each closure gets, bounds in generics, Box<dyn Fn> and returning closures.

Fn, FnMut and FnOnce are the three traits that describe things you can call: closures, function items and function pointers. They differ in what the call does to the captured state. FnOnce may consume it, so it can be called once. FnMut may change it, so it can be called many times but needs &mut access. Fn only reads it, so it can be called any number of times, even from several places at once.

The traits form a chain: every Fn is also FnMut, and every FnMut is also FnOnce. Because of that, a function that asks for FnOnce accepts the widest range of callers, and one that asks for Fn is the most restrictive. The compiler picks the traits for each closure automatically by looking at how its body uses the captured variables.

Rust
fn apply<F: Fn(i32) -> i32>(f: F, x: i32) -> i32 { f(x) }

Try it

Rust Three closures, three traits

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 Storing and returning closures

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 trait FnOnce<Args> { type Output; extern "rust-call" fn call_once(self, args: Args) -> Self::Output; }
pub trait FnMut<Args>: FnOnce<Args> { extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output; }
pub trait Fn<Args>: FnMut<Args> { extern "rust-call" fn call(&self, args: Args) -> Self::Output; }

You write the sugared form in bounds and types:

Rust
F: Fn(A, B) -> R
F: FnMut(A)
Box<dyn FnOnce() -> R + Send>
impl Fn(i32) -> i32
Trait Call receives Can be called Typical closure body
Fn &self any number of times, shared only reads captures
FnMut &mut self many times, one caller at a time changes captures
FnOnce self exactly once moves a capture out or drops it

Returns: the closure's result, -> R in the sugared syntax (the associated Output; omitted means ()).

Errors / panics / edge cases: you cannot implement these traits yourself on stable Rust; only closures, function items and pointers get them. Calling a FnMut through a non-mut binding is a compile error.

Usage notes

  • Capture mode and trait are different things. move decides how variables are captured (by value). The trait depends on what the body does with them. A move closure that only reads its data is still Fn.
  • Accept the weakest bound that works. Use FnOnce if you call the closure once (like Option::map or thread::spawn), FnMut for repeated calls (like Iterator::map), and Fn only when you must share it, for example across threads.
  • Bound by value or by reference. fn run(f: impl Fn()) takes it by value; fn run(f: &dyn Fn()) and &impl Fn() take a borrow. A &F is Fn whenever F is Fn, and &mut F is FnMut whenever F is FnMut.
  • Return types need impl or Box<dyn>. Each closure has a unique unnameable type, so write -> impl Fn(i32) -> i32 or box it.
  • Box<dyn FnOnce()> is callable directly, which makes it the usual type for queues of jobs.
  • Function items and fn pointers (non-capturing closures coerce to them) implement all three, so map(double) works.
  • Thread and async needs. thread::spawn requires FnOnce + Send + 'static; callbacks shared between threads need Fn + Send + Sync.
  • Generics compile to static dispatch and can be inlined. dyn Fn uses a vtable call, trading a little speed for flexibility.