Sub topic 5
Accepting closures as arguments
This chapter assumes you know ownership, borrowing, generics with trait bounds, and the three closure traits Fn, FnMut and FnOnce from the previous chapter. Here you will write functions that take closures and pick the right bound for each one.
Generic bounds
A closure has a unique, unnamed type, so you cannot write that type in a signature. Instead, take a generic parameter and bound it with 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(|n| n + offset, 1)); // 21
}The compiler generates a separate copy of apply_twice for each closure type passed in. This is called monomorphization, and it lets the call to f be inlined.
You can also write the bound with impl Trait or a where clause. These are equivalent:
fn run_a(f: impl Fn(i32) -> i32) -> i32 { f(1) }
fn run_b<F>(f: F) -> i32
where
F: Fn(i32) -> i32,
{
f(1)
}
fn main() {
println!("{} {}", run_a(|x| x + 1), run_b(|x| x * 5)); // 2 5
}Choosing the bound
Pick the loosest bound that still lets your function do its job. A looser bound accepts more closures.
| Bound | Your function may call it | Accepts |
|---|---|---|
| `FnOnce` | Once | Every closure |
| `FnMut` | Many times, needs `mut` access | Closures that are `FnMut` or `Fn` |
| `Fn` | Many times, even through a shared reference | Only `Fn` closures |
Here is an FnMut parameter. The function calls the closure repeatedly, and the closure updates a captured counter.
fn repeat<F: FnMut()>(times: u32, mut f: F) {
for _ in 0..times {
f();
}
}
fn main() {
let mut calls = 0;
repeat(3, || calls += 1);
println!("{}", calls); // 3
}Note mut f in the parameter list. Calling an FnMut needs a mutable borrow of f, so the binding must be mutable.
An FnOnce parameter lets callers pass a closure that consumes a captured value:
fn run_once<F: FnOnce() -> String>(f: F) -> String {
f()
}
fn main() {
let name = String::from("Ada");
let greeting = run_once(move || name + " says hi");
println!("{}", greeting); // Ada says hi
}If this parameter were Fn, the code would not compile, because name + ... moves name out of the closure.
Function pointers and trait objects
A plain function item also satisfies the closure traits, as long as it captures nothing:
fn double(x: i32) -> i32 { x * 2 }
fn main() {
let v: Vec<i32> = vec![1, 2, 3].into_iter().map(double).collect();
println!("{:?}", v); // [2, 4, 6]
}When you need to store closures of different types together, or avoid generics in a signature, take &dyn Fn(i32) -> i32 or Box<dyn Fn(i32) -> i32>. This uses dynamic dispatch, so each call goes through a pointer.
Exercise
You are writing fn call_three_times<F: ???>(f: F) that calls f() three times in a row, and callers should be able to pass a closure that increments a captured counter. Which bound do you use, and why can't it be FnOnce?
Show answer
Use FnMut(). The closure mutates captured state, so it is not Fn, and the function calls it several times, so it must not be FnOnce. An FnOnce bound allows only one call, because calling it consumes the closure. The parameter should be declared mut f: F.