skip to content

In a Rust retry helper that calls its operation up to `n` times, should the operation's bound be `Fn`, `FnMut` or `FnOnce`, and why?

level: middleimportance: must knowfreq 65%

answer

  1. how many times you call it
  2. the loosest bound that still works
  3. callers counting attempts
  4. mut binding and lending with &mut

basics

~20 s

FnMut. The helper calls the operation more than once, which rules out FnOnce, and FnMut is the loosest bound that allows repeated calls, so callers may pass closures that count attempts or change state. The parameter must be declared mut.

solid answer

~40 s

Pick the loosest bound the call pattern allows. A retry helper calls `op` repeatedly, so `FnOnce` fails inside the helper with E0382, because the first call moves `op`. `Fn` would compile but reject every caller whose closure mutates a capture, such as an attempt counter, with E0525 or E0594. `FnMut` accepts both those closures and plain `Fn` ones, so it is the right bound, and the parameter must be bound as `mut op: F`, or calling it is E0596. Std follows the same rule: `Iterator::map` and `Vec::retain` take `FnMut` because they call per item, while `Option::map` and `thread::spawn` take `FnOnce` because they call once. A caller who wants to keep its closure passes `&mut op`, which implements `FnMut` too.

code

rust · 27 lines
rust
fn retry<T, E>(attempts: u32, mut op: impl FnMut() -> Result<T, E>) -> Result<T, E> {
    let mut result = op();
    for _ in 1..attempts {
        if result.is_ok() {
            break;
        }
        result = op();
    }
    result
}

fn warm_up<F: FnMut() -> Result<u32, String>>(mut op: F) {
    let _ = op();
}

fn main() {
    let mut calls = 0;
    let mut flaky = || {
        calls += 1;
        if calls < 3 { Err(format!("timeout #{calls}")) } else { Ok(calls) }
    };
    warm_up(&mut flaky);          // lend it: &mut F is FnMut too
    let outcome = retry(5, &mut flaky);
    println!("{outcome:?}");      // Ok(3)
    println!("{:?}", retry(2, flaky));
    println!("total calls: {calls}");
}

go deeper

for a junior

Recall that a callback called many times cannot be FnOnce, and that FnMut needs a mut binding before you can call it.

for a middle

Explain choosing the loosest bound from the call pattern, the errors each wrong bound produces, and how &mut F lends an FnMut closure without moving it.

for a senior

Spot over-tight Fn bounds in review that force callers into RefCell, and argue for FnMut unless the API dispatches through &self or across threads.

for a principal

Public callback bounds are hard to tighten later; decide whether concurrency is planned before choosing between FnMut and Fn plus Sync for a library API.

## Choosing a bound from how you call it A trait bound on a callback is a promise in two directions: the function promises how it will call the closure, and in return it accepts every closure that can be called that way. The standard library's doc comments give the rule directly. Use `FnOnce` "when you … only need to call it once", `FnMut` when you "need to call it repeatedly, while allowing it to mutate state", and `Fn` when you need to call it repeatedly "and without mutating state (e.g., when calling it concurrently)". | How the API calls the closure | Loosest workable bound | Example | |---|---|---| | exactly once | `FnOnce` | `Option::map`, `thread::spawn` | | many times, one call at a time | `FnMut` | `Iterator::map`, `Vec::retain` | | many times through a shared reference, possibly from several threads at once | `Fn` | a handler shared behind `&self` | Because `Fn: FnMut: FnOnce`, a looser bound accepts strictly more closures. Choosing a tighter bound than you need costs callers something and gains you nothing, unless you need what the tighter bound allows. ## Why a retry helper wants `FnMut` A retry helper calls `op()`, checks the result and calls `op()` again if it failed. That rules out `FnOnce` immediately. Between the remaining two, the question is whether the helper ever needs to call `op` through a shared reference or from several threads at once. A sequential retry loop does not, so `FnMut` is the loosest bound that fits. It accepts: - closures that only read their captures, which are `Fn` and therefore also `FnMut`; - closures that mutate captures, such as one that increments an attempt counter or advances a mock's response list; - named functions and fn pointers, which implement all three traits. ## What each wrong choice costs 1. **`FnOnce`** fails inside the helper. rustc 1.99 reports E0382, "use of moved value: `op`", and adds the note "`FnOnce` closures can only be called once", pointing at the first call, which "causes it to be moved when called". 2. **`Fn`** compiles, but the cost lands on callers. A caller whose closure assigns to a capture gets E0594 if the closure is written inline in the call, or E0525, "expected a closure that implements the `Fn` trait, but this closure only implements `FnMut`", if it was bound to a variable first. The caller then has to reach for `Cell` or `RefCell` just to count attempts. 3. **`FnMut` without `mut` on the parameter** fails with E0596, "cannot borrow `op` as mutable, as it is not declared as mutable", because `call_mut` takes `&mut self`. The fix is `mut op: F`, which is local to the helper and invisible to callers. ## Lending an `FnMut` instead of giving it away A generic parameter takes the closure by value, so `retry(5, flaky)` moves `flaky` into the helper. When the caller wants to call the same closure again, or pass it to two helpers in turn, it passes `&mut flaky` instead. Std implements `FnMut` for `&mut F` whenever `F: FnMut`, so the reference satisfies the bound, the helper mutates the caller's closure in place and the caller gets it back when the call returns. The same works for `Fn` with `&F`. Inside a helper, the same trick lets you pass your own `FnMut` parameter on to a second generic function and keep using it: `inner(&mut op)`. ## When `Fn` is the right answer after all - The callback is stored and invoked through `&self`, for example by a handler registry that dispatches without exclusive access. - The callback is called from several threads at once, as a parallel retry or a shared request handler would, where `Fn + Sync` is the honest promise. - The API may want to start doing either of those later; tightening a public bound from `FnMut` to `Fn` breaks callers, so a library can choose `Fn` up front when concurrency is planned. ## Mistakes to avoid - Choosing `Fn` "to be safe": it is the strictest bound, not the safest. - Choosing `FnOnce` for a callback the code calls in a loop. - Cloning a closure to reuse it, which works only when every capture is `Clone` and nothing is captured by mutable reference; `&mut f` is the usual answer.

  • Inside the helper, how do you pass `op` to a second generic function and still call it afterwards?
    Pass `&mut op`. Because `&mut F` implements `FnMut` when `F` does, the inner function accepts the reference, calls the closure through it, and `op` is still yours when it returns. Passing `op` by value would move it and make a later call E0382.
  • When should a retry helper take `Fn` instead of `FnMut`?
    When it calls the operation through a shared reference or from several threads at once, for example a helper that fires parallel attempts. Then `Fn` plus `Send` and `Sync` as needed is the honest bound, and callers keep mutable state in a `Mutex` or atomics.
  • Why does `Option::map` take `FnOnce` while `Iterator::map` takes `FnMut`?
    `Option::map` calls its closure at most once, on the single value, so the loosest bound is `FnOnce` and callers may move captures out. `Iterator::map` calls its closure once per item, which needs repeated calls, so `FnMut` is the loosest bound that works.

  • Fn is the safest bound, so use it for every callback.
  • FnOnce means called once per iteration of a loop.
  • Reusing a closure after passing it requires cloning it.
  • An FnMut parameter can be called without a mut binding.
  • Iterator::map takes an Fn closure.