Sub topic 5
Accepting closures as arguments
This chapter assumes you know ownership and borrowing, generics with trait bounds, and the Fn, FnMut and FnOnce traits from the previous chapter. Here you will write functions that take closures, choose the right bound, and fix the compiler errors that appear when the bound and the closure disagree.
Why a generic parameter
Every closure has its own anonymous type. No two closures share a type, even when their code is identical. A function cannot name that type, so it accepts a closure through a generic parameter bounded by one of the closure traits.
fn apply_twice<F: Fn(i32) -> i32>(f: F, x: i32) -> i32 {
f(f(x))
}
fn main() {
let offset = 10;
println!("{}", apply_twice(|x| x + offset, 1)); // 21
}The bound F: Fn(i32) -> i32 says that F can be called with an i32 through a shared reference and returns an i32. The compiler generates a separate copy of apply_twice for each distinct closure passed in. This is called monomorphization. It lets the compiler inline the closure body into the function.
Three equivalent spellings
You can write the same bound three ways.
fn a<F: Fn(i32) -> i32>(f: F, x: i32) -> i32 { f(x) }
fn b<F>(f: F, x: i32) -> i32
where
F: Fn(i32) -> i32,
{
f(x)
}
fn c(f: impl Fn(i32) -> i32, x: i32) -> i32 { f(x) }
fn main() {
let k = 2;
let g = |x| x * k;
println!("{} {} {}", a(&g, 5), b(&g, 5), c(&g, 5)); // 10 10 10
}| Form | Use it when |
|---|---|
| `<F: Fn(..)>` | The bound is short, or you need to name `F` elsewhere (for example in a struct or a second parameter of the same type). |
| `where F: Fn(..)` | There are several type parameters or long bounds, as in a signature with `T`, `E` and `F`. |
| `impl Fn(..)` | You use the closure once and never need its name. This is the shortest form. |
With impl Trait in argument position, callers cannot specify the type explicitly. That is rarely a problem for closures, because you could not write the type anyway.
Notice that a(&g, 5) passes a reference. A shared reference &F implements Fn whenever F does. A mutable reference &mut F implements FnMut whenever F: FnMut. So a caller can lend a closure and keep using it afterward.
Choosing the bound
Pick the weakest requirement your function needs. A weaker bound accepts more closures. The order of strictness is FnOnce (accepts everything), then FnMut, then Fn (accepts the fewest).
FnMut: called repeatedly, may change state
fn repeat<F: FnMut()>(mut f: F, times: u32) {
for _ in 0..times {
f();
}
}
fn main() {
let mut calls = 0;
repeat(|| calls += 1, 3);
println!("{}", calls); // 3
}The parameter must be declared mut f, because calling an FnMut closure needs &mut self. The closure borrows calls mutably, and that borrow ends when repeat returns, so calls is readable afterward.
FnOnce: called at most once, may consume captures
fn run_once<F: FnOnce() -> String>(f: F) -> String {
f()
}
fn main() {
let name = String::from("Ada");
let greeting = run_once(|| name); // the closure moves `name` out
println!("{}", greeting); // Ada
}Returning name from the closure moves it out of the captured environment, so the closure can run only once. If run_once declared Fn or FnMut, this call would not compile.
Fn: called repeatedly with no mutation
Use Fn when you must call the closure through &self. Typical cases are calling it from several threads (together with Sync), storing it in a structure that is read through shared references, or calling it inside another closure that is itself Fn. If none of those apply, FnMut is usually the more permissive choice.
A realistic example: retry with a closure
Generic return types combine naturally with closure bounds. This function retries an operation and passes the attempt number to it.
fn retry<T, E, F>(mut attempt: F, max: u32) -> Result<T, E>
where
F: FnMut(u32) -> Result<T, E>,
{
let mut n = 1;
loop {
match attempt(n) {
Ok(v) => return Ok(v),
Err(e) if n >= max => return Err(e),
Err(_) => n += 1,
}
}
}
fn main() {
let mut log = Vec::new();
let result: Result<u32, String> = retry(
|n| {
log.push(n);
if n < 3 {
Err(format!("fail {}", n))
} else {
Ok(n * 10)
}
},
5,
);
println!("{:?} {:?}", result, log); // Ok(30) [1, 2, 3]
}The bound is FnMut because the function calls the closure several times and the closure pushes onto log. The caller never has to write T, E or F, since inference fills them in from the closure body and the annotated result.
Function pointers and trait objects
Generics are not the only option.
- A function pointer type
fn(i32) -> i32accepts named functions and closures that capture nothing. A capturing closure cannot coerce to it. - A trait object
&dyn Fn(i32) -> i32(or&mut dyn FnMut(..)) uses dynamic dispatch. There is one compiled copy of the function, and each call goes through a vtable.
fn call_dyn(f: &dyn Fn(i32) -> i32, x: i32) -> i32 {
f(x)
}
fn call_ptr(f: fn(i32) -> i32, x: i32) -> i32 {
f(x)
}
fn double(x: i32) -> i32 {
x * 2
}
fn main() {
let k = 5;
let add = |x| x + k;
println!("{}", call_dyn(&add, 1)); // 6
println!("{}", call_dyn(&double, 2)); // 4
println!("{}", call_ptr(double, 3)); // 6
println!("{}", call_ptr(|x| x + 1, 4)); // 5
}Every fn pointer also implements Fn, FnMut and FnOnce. A generic bound such as F: Fn(i32) -> i32 therefore accepts plain functions too, and it is usually the better default for APIs. Use dyn when you want to store closures of different types together, for example in a Vec<Box<dyn Fn(i32) -> i32>>, or when you want to limit code size.
| Approach | Dispatch | Accepts capturing closures | Can mix different closures in one collection |
|---|---|---|---|
| Generic `F: Fn(..)` | Static, inlinable | Yes | No |
| `&dyn Fn(..)` / `Box<dyn Fn(..)>` | Dynamic | Yes | Yes |
| `fn(..)` pointer | Indirect call | No | Yes (same signature) |
Common errors
Other mistakes to watch for:
- Forgetting
muton anFnMutparameter. The error says you cannot borrowfas mutable. Writemut f: F. - Using a closure after passing it by value. A closure that captures only non-
Copydata by move is itself notCopy, so the call consumes it. Pass&closureor&mut closure, or clone the captured data. - Over-strict bounds in your own API. Requiring
Fnwhen you only call the closure in a loop on one thread needlessly rejects closures that update state. - Passing a capturing closure where
fn(..)is expected. Switch to a generic bound or&dyn Fn. - Borrowed arguments. A bound like
F: Fn(&str) -> usizeworks for any lifetime of the argument. The compiler treats it as a higher-ranked bound, so you do not write lifetimes yourself.
Exercise
Write a function for_each_pair that takes a slice &[i32] and a closure, and calls the closure with each element together with its index, as f(index, value). Which bound should the closure have, and why? Show a call that collects the sum of index * value into a local variable.
Show answer
Use FnMut(usize, i32). The function calls the closure many times, and the caller wants to update a captured variable, which Fn forbids. FnOnce would allow only one call.
fn foreachpair<F: FnMut(usize, i32)>(items: &[i32], mut f: F) {
for (i, &v) in items.iter().enumerate() {
f(i, v);
}
}
fn main() {
let mut total = 0;
foreachpair(&[4, 5, 6], |i, v| total += i as i32 v);
println!("{}", total); // 04 + 15 + 26 = 17
}