Sub topic 13
Passing closures and function pointers
This chapter assumes you can write and call functions with typed parameters and return values. It also assumes you know let and let mut, and that you have met ownership and borrowing in outline. By the end you should be able to accept a closure or a function as an argument, pick the right trait bound, and read the compiler errors that appear when you pick the wrong one.
Functions as values
A function can take another function as an argument. This lets the caller decide part of the behavior. The usual tool is a generic parameter with a closure trait bound:
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));
}This prints 8 and then 5. The bound F: Fn(i32) -> i32 says that F is any type that can be called with one i32 and returns an i32. Both a named function and a closure satisfy it.
A closure is an anonymous function written as |parameters| body. Parameter and return types are usually inferred from how the closure is used. A closure can also use variables from the scope where it is written. This is called capturing, and it is the main difference between a closure and a plain function.
What closures capture
Rust captures each variable in the least demanding way the closure body allows. It uses a shared borrow if the body only reads the variable. It uses a mutable borrow if the body modifies it. It moves the variable in if the body consumes it, for example by returning an owned String.
The way a closure uses its captures decides which of three traits it implements.
| Trait | The closure may | How many times it can be called |
|---|---|---|
| `Fn` | Only read captured values | Any number of times, even through a shared reference |
| `FnMut` | Modify captured values | Any number of times, but it needs `&mut` access |
| `FnOnce` | Move captured values out | At least once, and only once if it moves something out |
The traits form a hierarchy. Every Fn closure is also FnMut, and every FnMut closure is also FnOnce. So FnOnce is the most permissive bound for the caller, and Fn is the most demanding. When you write a function that takes a closure, ask for the weakest trait your code needs. A function that calls its argument once should use FnOnce, because that accepts the most callers.
FnMut: closures that change state
If a closure modifies a captured variable, the receiving function needs FnMut. The parameter must also be declared mut, because calling an FnMut closure needs mutable access to the closure itself:
fn call_twice<F: FnMut()>(mut f: F) {
f();
f();
}
fn main() {
let mut count = 0;
call_twice(|| count += 1);
println!("{count}");
}This prints 2. The closure borrows count mutably for as long as call_twice runs. After the call returns, the borrow ends and main can read count again.
If you changed the bound to Fn(), the program would not compile. The compiler reports that the closure is FnMut because it mutates a captured variable, so it cannot be used where Fn is required.
FnOnce and the move keyword
A closure that gives away something it captured can run only once. After the first call the value is gone:
fn run_once<F: FnOnce() -> String>(f: F) -> String {
f()
}
fn main() {
let name = String::from("Ada");
let greeting = run_once(move || {
let owned = name;
format!("hello {owned}")
});
println!("{greeting}");
}Inside the closure, let owned = name; moves name out of the closure's captured state, so the closure is FnOnce only. The move keyword is a separate concern. It forces the closure to take ownership of every variable it captures, even ones it only reads. This is needed when the closure must outlive the scope that created it, for example when you return it from a function or send it to another thread. A move closure is not automatically FnOnce. If it only reads its captured values, it is still Fn.
Three ways to accept a callable
The generic bound is not the only way to take a closure. The choice affects speed, flexibility, and syntax.
| Form | Example | Dispatch | Accepts capturing closures |
|---|---|---|---|
| Generic parameter | `fn f<F: Fn(i32) -> i32>(g: F)` | Static, inlined per type | Yes |
| `impl Trait` argument | `fn f(g: impl Fn(i32) -> i32)` | Static, same as generic | Yes |
| Trait object | `fn f(g: &dyn Fn(i32) -> i32)` | Dynamic, one shared copy | Yes |
| Function pointer | `fn f(g: fn(i32) -> i32)` | Indirect call | Only non-capturing |
Generics and impl Trait produce a specialized copy of the function for each closure type. The compiler can often inline the call, so there is no runtime cost. The price is more compiled code. A trait object (&dyn Fn) uses one compiled copy and looks up the call at runtime. Choose it when you want to keep different closures in one collection, or when you want to limit code size.
The impl Trait form is shorthand for a generic parameter. One difference is that you cannot name the type, so callers cannot supply it with turbofish syntax.
Function pointers
The type fn(i32) -> i32, written with a lowercase fn, is a function pointer. It points to a function with that exact signature. A function pointer holds no captured data, so it is a plain address. Do not confuse it with the Fn trait, which has a capital F.
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, 3));
println!("{}", apply_ptr(|x| x + 1, 3));
}This prints 9 and then 4. The second call works because a closure that captures nothing can convert to a function pointer. If the closure used a local variable such as let offset = 10;, the call would be rejected with a type mismatch, because that closure carries data and has no plain address.
Function pointers implement all three traits Fn, FnMut, and FnOnce. A function that takes F: Fn(i32) -> i32 therefore also accepts a function pointer. The reverse is not true. Prefer a trait bound in your own APIs, and use fn pointers when you need a plain, data-free type. Examples are a table of handlers stored in an array, or code that talks to C.
Named functions and some constructors can be passed wherever a closure is expected. The standard iterator methods use this a lot:
fn double(x: i32) -> i32 {
x * 2
}
fn main() {
let doubled: Vec<i32> = vec![1, 2, 3].into_iter().map(double).collect();
println!("{:?}", doubled);
let words: Vec<String> = ["a", "b"].iter().map(|s| s.to_uppercase()).collect();
println!("{:?}", words);
}Passing double directly is shorter than writing |x| double(x), and it behaves the same.
Returning closures
Every closure has its own unnamed type, so you cannot write that type in a return position. There are two common solutions.
Use impl Fn when the function returns one kind of closure. Use Box<dyn Fn> when different branches return different closures, or when you store several in a collection:
fn make_adder(n: i32) -> impl Fn(i32) -> i32 {
move |x| x + n
}
fn main() {
let ops: Vec<Box<dyn Fn(i32) -> i32>> = vec![
Box::new(|x| x + 1),
Box::new(|x| x * 2),
Box::new(make_adder(10)),
];
for op in &ops {
println!("{}", op(5));
}
}This prints 6, 10, and 15. The move in make_adder is required. Without it, the closure would borrow the parameter n, which is dropped when make_adder returns. The compiler reports that the closure may outlive the current function and suggests move.
The Vec needs Box<dyn Fn> because each closure in it has a different type, and a Vec holds one element type. impl Fn would fail here for that reason.
Common errors
The following mistakes come up often, along with how to read them.
- Bound too strong. A closure that mutates state passed to an
Fnparameter fails with a message saying it isFnMut. Loosen the bound toFnMut, or change the closure so it no longer mutates. - Missing
muton the parameter. Calling anFnMutargument without declaring itmut f: Fproduces a "cannot borrow as mutable" error. - Calling an
FnOncetwice. The compiler reports a use of a moved value. Either call it once, or requireFnorFnMutand change the closure to clone instead of move. - Borrow conflicts. A closure that captures a variable by mutable borrow holds that borrow until its last use. Reading the variable in between is an error. Finish using the closure first, or restructure the code.
- Capturing closure passed as
fn. A closure that uses a local variable cannot become a function pointer. Switch the parameter to a genericF: Fn(...). - Returning a closure without
move. A closure that refers to a local variable cannot outlive it. Addmove.
Choosing between the options
Start with a generic bound or impl Fn. It is the default because it is fast, accepts every closure, and needs no allocation. Pick the weakest of FnOnce, FnMut, and Fn that your function body allows. Use Box<dyn Fn> when you need to store closures of different types or choose one at runtime. Use fn pointers only when you specifically need a data-free callable type.
Exercise
Write a function repeat_n that takes a count n: usize and a closure f, and calls f exactly n times. Which trait bound should f have if the caller wants to pass || total += 1, where total is a local i32? What would change if the closure were || println!("hi")?
Show answer
Use FnMut(), because the closure modifies total. Declare the parameter as mut f: F:
fn repeatn<F: FnMut()>(n: usize, mut f: F) {
for in 0..n {
f();
}
}
The println! closure only reads, so it implements Fn, and it is also accepted by the FnMut bound, since every Fn closure is FnMut. Nothing needs to change. An Fn bound would reject the total += 1 closure, and an FnOnce bound would reject the call inside the loop, because f would be moved on the first iteration.
Exercise
Why does fn make_counter() -> impl Fn() -> i32 { let mut n = 0; move || { n += 1; n } } not compile, and what return type fixes it?
Show answer
The closure mutates its captured n, so it is FnMut, not Fn. The declared impl Fn() -> i32 promises more than the closure delivers. Change the return type to impl FnMut() -> i32. The caller then binds the result with let mut counter = make_counter(); so that calling it is allowed.