Skip to content

Specify How a Callback May Capture State

The Course
•
30 min study

A trait object lets a caller choose behavior; a closure lets a caller supply it inline, along with whatever state it captures. A ledger traversal might report each accepted quantity to a callback that prints it, counts it or pushes it into a list. The traversal does not care which, but it must say what it will do with the callback, and the closure traits are how it says so.

There are three, and they describe how a closure may be called. Fn closures only read what they capture, so they can be called any number of times through a shared reference. FnMut closures may change captured state, so each call needs exclusive access. FnOnce closures may consume what they capture, so they can be called only once. Every closure implements FnOnce; one that does not move captured values out also implements FnMut; one that does not mutate also implements Fn. A bound is therefore a contract in two directions. The looser the bound a function asks for, the more closures callers can pass in, and the less the function itself is allowed to do with them.

Predict and run

How many callback invocations append a value, and what does main see afterward?

Predict, then run Rust
fn visit(values: &[u32], mut observe: impl FnMut(u32)) {
    for value in values {
        observe(*value);
    }
}

fn main() {
    let mut seen = Vec::new();
    visit(&[2, 4, 6], |value| seen.push(value));
    println!("{seen:?}");
}
Check your prediction
Text
[2, 4, 6]

The closure captures seen by mutable reference, and visit calls it three times. The parameter is declared mut observe because calling an FnMut needs &mut access to the closure. When visit returns, the closure is dropped and its borrow of seen ends, so main can read the vector. Now change the bound to impl Fn(u32) and predict the result. The compiler reports error[E0596] and says it cannot borrow seen as mutable, as it is a captured variable in a Fn closure. The error points at the closure, not at visit: the caller's closure no longer meets the contract. Restore FnMut afterward.

Each bound in action

The three functions below each ask for a different bound and call their callback accordingly. Read each signature and decide what kind of closure it can accept.

Fn, FnMut and FnOnce side by side Rust
fn call_twice(f: impl Fn() -> u32) -> u32 {
    f() + f()
}

fn call_counted(mut f: impl FnMut() -> u32) -> u32 {
    f();
    f()
}

fn call_once(f: impl FnOnce() -> String) -> String {
    f()
}

fn main() {
    let limit = 10;
    println!("Fn: {}", call_twice(|| limit));

    let mut calls = 0;
    println!("FnMut: {}", call_counted(|| { calls += 1; calls }));
    println!("calls after: {calls}");

    let name = String::from("bolt");
    println!("FnOnce: {}", call_once(move || name));
    println!("FnOnce with a plain closure: {}", call_once(|| String::from("nut")));
}
Text
Fn: 20
FnMut: 2
calls after: 2
FnOnce: bolt
FnOnce with a plain closure: nut

move || name returns the captured String itself, which moves it out of the closure, so that closure is only FnOnce. The last line passes a closure that implements all three traits to the most permissive bound. The reverse direction is what fails: inside call_once, calling f() a second time is error[E0382]: use of moved value for f, because calling an FnOnce consumes it.

That gives a simple rule for choosing. Ask for FnOnce if you call the callback at most once, FnMut if you call it repeatedly from one place, and Fn only if you must call it through a shared reference, for example from several places at once or from another thread. Each step up removes closures callers could otherwise pass.

Borrows last as long as the closure

A closure that captures by mutable reference holds that borrow for as long as the closure exists, not only while it runs. Keeping the closure in a local variable makes this visible:

Rust
let mut seen = Vec::new();
let mut record = |value: u32| seen.push(value);
record(1);
println!("{seen:?}");
record(2);

This fails with error[E0502]: cannot borrow seen as immutable because it is also borrowed as mutable. The closure still holds its mutable borrow at println!, because it is used again on the next line. Move the print after the last call and the code compiles. Passing the closure straight into visit, as in the first example, avoids the problem entirely: the closure is dropped when visit returns.

move changes what a closure captures, which has a surprising effect on Copy values:

A move closure copies a Copy counter Rust
fn main() {
    let mut count = 0;
    let mut bump = move || {
        count += 1;
        count
    };
    println!("first call: {}", bump());
    println!("second call: {}", bump());
    println!("outside: {count}");
}
Text
first call: 1
second call: 2
outside: 0

move copied the integer into the closure, so the closure increments its own copy and the outer count never changes. With a Vec, move would have moved the vector into the closure and the outer variable could not be used at all. Use move when the closure must outlive the current scope, and leave it off when you want the caller's state to change.

impl FnMut or dyn FnMut

impl FnMut(u32) in a parameter is a generic: the function is compiled once per closure type, and calls can be inlined. &mut dyn FnMut(u32) compiles the function once and calls the closure through a vtable. Prefer impl by default; choose dyn to store callbacks of different types together, or to keep a large function from being duplicated.

Practice

Exercise

Your turn

Write visit_positive(values: &[i32], observe: impl FnMut(i32)) that calls its observer only for values greater than zero. In main, visit [-2, 0, 3, 5], collect the observed values into a vector, assert that it equals vec![3, 5] and print it.

Your working space Rust
fn main() {
    // Visit [-2, 0, 3, 5] and collect the positive values.
}
Hint 1: the idea

Keep the selection rule in the traversal and the recording behavior in the closure. Zero is not positive, so it must be skipped too.

Hint 2: a first step

Write the signature first. The closure records values, so it changes what it captured: pick the closure trait that allows that, and remember what the parameter binding then needs. The loop body comes after.

Worked solution
Run the solution Rust
fn visit_positive(values: &[i32], mut observe: impl FnMut(i32)) {
    for value in values {
        if *value > 0 {
            observe(*value);
        }
    }
}

fn main() {
    let mut seen = Vec::new();
    visit_positive(&[-2, 0, 3, 5], |value| seen.push(value));
    assert_eq!(seen, vec![3, 5]);
    println!("{seen:?}");
}
Text
[3, 5]

The traversal owns the rule and the closure owns the effect, so the same visit_positive could count values with |_| count += 1 or sum them with |v| total += v without any change. FnMut is the right bound because the function calls the observer repeatedly from one loop; Fn would reject all three of those closures. The checkpoint next combines this callback with a boxed rule.

Was this article helpful?

Your response is saved on this device.