Sub topic 13
Passing closures and function pointers
This chapter assumes you can define functions with typed parameters and return values, and that you know basic ownership and borrowing. Here you will write functions that accept other functions or closures as arguments.
Closures in brief
A closure is an anonymous function that can capture variables from the scope where it is written. Its parameters go between pipes, and the body follows.
fn main() {
let offset = 10;
let add_offset = |x: i32| x + offset;
println!("{}", add_offset(5));
}A named function cannot use offset like this. The closure can, because it captures the variable.
Accepting a closure with a generic bound
To take a closure as a parameter, declare a generic type and bound it with a trait that describes the call signature.
fn apply<F: Fn(i32) -> i32>(f: F, x: i32) -> i32 {
f(x)
}
fn double(x: i32) -> i32 {
x * 2
}
fn main() {
println!("{}", apply(double, 4));
println!("{}", apply(|x| x + 1, 4));
}F: Fn(i32) -> i32 means "any type that can be called with an i32 and returns an i32". Both the named function double and the closure |x| x + 1 satisfy it. The compiler generates a specialized copy of apply for each type you pass, so the call has no runtime indirection.
Fn, FnMut, and FnOnce
The three closure traits differ in how the closure uses what it captured.
| Trait | What the closure does with captures | How often it can be called |
|---|---|---|
| `Fn` | Only reads them | Many times, even through a shared reference |
| `FnMut` | Changes them | Many times, needs mutable access |
| `FnOnce` | Moves them out or consumes them | Once |
Every closure that can be called many times implements FnOnce, and Fn closures also implement FnMut. So FnOnce is the most permissive bound for the caller, and Fn is the most restrictive. Choose the loosest bound your function body needs.
fn call_twice<F: FnMut()>(mut f: F) {
f();
f();
}
fn main() {
let mut count = 0;
call_twice(|| count += 1);
println!("{count}");
}The closure changes count, so Fn would be rejected. FnMut works. The parameter must be declared mut f because calling an FnMut needs mutable access.
Function pointers
The type fn(i32) -> i32 (lowercase fn) is a function pointer. It refers to a named function or to a closure that captures nothing.
fn square(x: i32) -> i32 {
x * x
}
fn apply_ptr(f: fn(i32) -> i32, x: i32) -> i32 {
f(x)
}
fn main() {
println!("{}", apply_ptr(square, 6));
println!("{}", apply_ptr(|x| x - 1, 6));
}A function pointer implements Fn, FnMut, and FnOnce, so you can pass one anywhere a closure bound is expected. The reverse is not true. A closure that captures offset cannot be passed where fn(i32) -> i32 is required.
Common errors
- Using
Fnwhen the closure mutates a captured variable. The compiler reports that the closure isFnMut. Change the bound. - Forgetting
muton anFnMutparameter. Writemut f: F. - Passing a capturing closure to a
fnpointer parameter. Use a genericF: Fn(...)instead. - Calling an
FnOnceclosure twice. The first call moves the captured value, so the second call is a compile error.
Returning closures
A closure has a unique unnameable type, so a return type uses impl Fn.
fn make_adder(n: i32) -> impl Fn(i32) -> i32 {
move |x| x + n
}
fn main() {
let add5 = make_adder(5);
println!("{}", add5(3));
}The move keyword copies n into the closure, so the closure stays valid after make_adder returns.
Exercise
You write fn run<F: Fn()>(f: F) { f(); } and call let mut n = 0; run(|| n += 1);. The compiler rejects it. What is the smallest change to run that fixes it?
Show answer
The closure mutates n, so it is FnMut, not Fn. Change the signature to fn run<F: FnMut()>(mut f: F) { f(); }. The mut on the parameter is required to call it.
Exercise
Why can apply_ptr(|x| x - 1, 6) compile, while let k = 3; apply_ptr(|x| x - k, 6) does not?
Show answer
The first closure captures nothing, so it coerces to the function pointer type fn(i32) -> i32. The second captures k, which a plain function pointer cannot carry, so it needs a generic Fn bound.