skip to content

In Rust, how do `Fn`, `FnMut` and `FnOnce` differ, and how does the compiler decide which of them a closure implements?

level: juniorimportance: must knowfreq 75%

answer

  1. three receivers for one call
  2. a supertrait chain
  3. what the body does with captures
  4. moving a capture out of the body

basics

~20 s

Fn is called through &self, FnMut through &mut self and FnOnce by value. Every closure implements FnOnce; one that never moves a captured value out also implements FnMut, and one that also never mutates a capture implements Fn.

solid answer

~40 s

The three traits differ in the receiver of the call: `Fn::call` takes `&self`, `FnMut::call_mut` takes `&mut self` and `FnOnce::call_once` takes `self`. They form a chain, `Fn: FnMut: FnOnce`, so an `Fn` closure is accepted wherever `FnMut` or `FnOnce` is asked for, and every closure is at least `FnOnce`. rustc chooses from what the body does with its captures: a closure that only reads them is `Fn`, one that assigns to a capture or calls a `&mut self` method on it is `FnMut` but not `Fn`, and one that moves a captured value out, by returning it or passing it to a by-value function, is only `FnOnce`. The `move` keyword does not change this: it decides how values get into the closure, not what the body does with them.

code

rust · 18 lines
rust
fn call_twice<F: Fn() -> usize>(f: F) -> usize { f() + f() }
fn call_twice_mut<F: FnMut() -> usize>(mut f: F) -> usize { f() + f() }
fn call_once<F: FnOnce() -> String>(f: F) -> String { f() }

fn main() {
    let name = String::from("retry");
    let reads = || name.len();                 // only reads `name`: Fn
    let mut calls = 0;
    let mut counts = || { calls += 1; calls }; // mutates `calls`: FnMut
    let token = String::from("secret");
    let gives_away = move || token;            // moves `token` out: FnOnce only

    println!("{}", call_twice(&reads));        // &F is Fn too, so `reads` stays usable
    println!("{}", call_twice_mut(&mut counts));
    println!("{}", call_twice_mut(reads));     // an Fn closure also satisfies FnMut
    println!("{}", call_once(gives_away));
    println!("calls = {calls}");
}

go deeper

for a junior

Recall the three receivers, &self, &mut self and self, and that a closure's body decides which traits it gets. Being able to classify a reading, a mutating and a consuming closure on sight is the bar.

for a middle

Explain the supertrait chain and why it makes Fn closures acceptable everywhere. Show that move changes capture, not the trait, and that Cell keeps a counting closure Fn.

for a senior

Read E0525 and E0594 and know which bound or which line of the body to change. Lend closures as &F or &mut F instead of cloning them, and keep bounds as loose as the call pattern allows.

for a principal

Treat the bound on a public callback as an API promise: tightening FnMut to Fn later breaks callers, while loosening is compatible. Review new callback APIs for the loosest bound they can honestly keep.

## The three call traits A **closure** in Rust is a value of a unique, anonymous type that the compiler generates for each closure expression. Calling it, `f(x)`, is a method call on one of three traits from `core::ops`, re-exported as `std::ops`. They differ only in how the call receives the closure: | Trait | Call method | Receiver | What a caller may do | |---|---|---|---| | `Fn` | `call` | `&self` | call it any number of times, even through a shared reference | | `FnMut` | `call_mut` | `&mut self` | call it repeatedly, but needs unique access each time | | `FnOnce` | `call_once` | `self` | call it once; the call consumes the value | The standard library's own doc comments put it the same way: instances of `Fn` "can be called repeatedly without mutating state", instances of `FnMut` "can be called repeatedly and may mutate state", and an `FnOnce` "might not be callable multiple times". ## The supertrait chain The traits are declared as `trait Fn<Args>: FnMut<Args>` and `trait FnMut<Args>: FnOnce<Args>`. That has three practical consequences: - **Every closure implements `FnOnce`**, because anything callable can be called at least once. - An `Fn` closure can be passed to a parameter bounded by `FnMut` or `FnOnce`. - An `FnMut` closure can be passed where `FnOnce` is expected, but not where `Fn` is. So the bound an API writes is a promise about how it calls the closure, and the set of closures it accepts shrinks as the bound tightens from `FnOnce` to `FnMut` to `Fn`. ## How rustc decides for a closure The Reference states the rule in terms of the captured variables, and it is checked against the body, not the declaration: 1. A closure that **does not move out of** any captured variable implements `FnMut`. 2. A closure that **does not mutate or move out of** any captured variable implements `Fn`. 3. Every closure implements `FnOnce`, whatever its body does. Some concrete cases: - `|| name.len()` only reads `name`, so it is `Fn`, `FnMut` and `FnOnce`. - `|| { calls += 1; calls }` assigns to a capture, so it is `FnMut` and `FnOnce`, not `Fn`. - `|| v.push(2)` calls a `&mut self` method on a captured `Vec`, so it is also `FnMut`. - `move || token` returns a captured `String`, moving it out, so it is only `FnOnce`. - `|| hits.set(hits.get() + 1)` on a captured `Cell` only takes `&` to the cell, so it stays `Fn`: **interior mutability** does not count as mutating the capture. Copying a `Copy` capture is a read, not a move, so returning a captured `i32` keeps a closure `Fn`. The **`move` keyword** is a separate question. It forces captures to be taken by value, which matters for how long the closure may live, but the Reference notes that `move` closures "may still implement `Fn` or `FnMut`" because the traits are "determined by what the closure does with captured values, not how it captures them". `move || token.len()` is therefore `Fn`. How each variable is captured belongs to the material on closure captures; this question is only about the call traits. ## What rustc reports when the trait is wrong The diagnostic depends on where the closure is written. If the closure is bound to a variable first and then passed to `fn call_twice<F: Fn() -> usize>(f: F)`, rustc 1.99 reports **E0525**: "expected a closure that implements the `Fn` trait, but this closure only implements `FnMut`", pointing at the assignment that made it `FnMut`. If the same closure is written inline in the call, the bound is known while the closure is checked, and rustc reports **E0594**, "cannot assign to `calls`, as it is a captured variable in a `Fn` closure", with a hint to change the parameter to accept `FnMut`. ## Function pointers and references - Safe function pointers such as `fn(i32) -> i32`, and named functions, implement all three traits. - For any `F: Fn`, `&F` implements `Fn` too, so `call_twice(&reads)` lends a closure and keeps it usable. - For any `F: FnMut`, `&mut F` implements `FnMut`, which is how an `FnMut` closure is lent to a function and reused afterwards. ## Common mistakes - Thinking `move` makes a closure `FnOnce`; it changes the capture, not the trait. - Thinking `FnMut` excludes `FnOnce`; the supertrait chain means it includes it. - Treating `Fn` and `fn` as the same thing; one is a trait, the other a pointer type.

  • Why does passing `&reads` to a function bounded by `F: Fn()` work, and why do it?
    Because std implements `Fn` for `&F` whenever `F: Fn`, so a shared reference to an `Fn` closure is itself an `Fn` closure. Passing `&reads` lends the closure instead of moving it, and the caller can keep calling `reads` afterwards. The same trick for `FnMut` is `&mut f`.
  • A closure only calls `cell.set(...)` on a captured `Cell<u32>`; is it `Fn` or `FnMut`?
    It is `Fn`. `Cell::set` takes `&self`, so the closure only needs a shared borrow of the cell and never mutates or moves the capture itself. Interior mutability is the usual way to keep state in a callback that must be `Fn`.
  • Does a closure that returns a captured `i32` implement `Fn`?
    Yes. `i32` is `Copy`, so returning it copies the value out instead of moving it, and the closure can be called again. Only moving out a non-`Copy` capture, such as returning a captured `String`, restricts a closure to `FnOnce`.

  • A move closure always implements only FnOnce.
  • An FnMut closure cannot be passed where FnOnce is expected.
  • A closure that calls Cell::set on a capture must be FnMut.
  • You pick a closure's trait by annotating it, like a type.
  • Fn and the fn pointer type are the same thing.