Blog

Part 16 · Closures in Rust: Fn, FnMut, FnOnce and What They Capture

A closure is a small function you write in place, and it can use the variables around it. This part shows how a closure captures them, by reference, by mutable reference or by value, and what Fn, FnMut and FnOnce mean.

A closure is a small function you write right where you need it. Unlike a normal function, it can use the variables around it. We’ve already met a few: retain in Part 8, map_err in Part 12 and and_modify in Part 13. Each time, we read the |x| ... part on trust. This part explains it.

We’ll cover closure syntax, how a closure captures the variables it uses, the three traits Fn, FnMut and FnOnce, move closures, and passing closures into and out of functions. It builds on borrowing from Part 7 and generics from Part 15. Every program here was run on Rust 1.95, and its output is pasted from the run.

Try this first

tick is a closure that adds 1 to count. We call it, print count, and call it again. What does this print?

fn main() {
    let mut count = 0;
    let mut tick = || count += 1;
    tick();
    println!("{count}");
    tick();
}

It doesn’t print anything. It doesn’t compile:

error[E0502]: cannot borrow `count` as immutable because it is also borrowed as mutable
 --> src/main.rs:5:16
  |
3 |     let mut tick = || count += 1;
  |                    -- ----- first borrow occurs due to use of `count` in closure
  |                    |
  |                    mutable borrow occurs here
4 |     tick();
5 |     println!("{count}");
  |                ^^^^^ immutable borrow occurs here
6 |     tick();
  |     ---- mutable borrow later used here

The error says the closure borrowed count, mutably, on line 3. That’s the “one writer” from Part 7. The closure holds that borrow for as long as it might still be called, and it’s called again on line 6. So on line 5, println! can’t read count. By the end of this part, every line of that message will make sense, and we’ll fix it two ways.

A function you write in place

Here’s a normal function and a closure that do the same job:

fn add_one(x: i32) -> i32 {
    x + 1
}

fn main() {
    let add_one_closure = |x| x + 1;
    println!("{}", add_one(5));
    println!("{}", add_one_closure(5));

    let add = |a: i32, b: i32| -> i32 { a + b };
    let say_hi = || println!("hi");
    println!("{}", add(2, 3));
    say_hi();
}

It prints:

6
6
5
hi

The parameters go between two bars, |x|, instead of in brackets. The body comes after. || means “no parameters”. You call a closure the same way you call a function, with brackets: add_one_closure(5).

A closure can be stored in a variable, like add_one_closure, or passed straight to another function. The second is the usual case. When you write names.retain(|n| n.len() > 2), the closure goes straight into retain.

You can write the types out, as add does. If you write the return type, the body must be in braces. Most of the time you don’t write types at all. The compiler works them out from how the closure is used.

Types are worked out once, then fixed

A closure without written types gets its types from its first use. After that, they don’t change. This closure just hands back whatever it’s given:

fn main() {
    let same = |x| x;
    let a = same(5);
    let b = same("five");
    println!("{a} {b}");
}

It prints:

error[E0308]: mismatched types
 --> src/main.rs:4:18
  |
4 |     let b = same("five");
  |             ---- ^^^^^^ expected integer, found `&str`
  |             |
  |             arguments to this function are incorrect
  |
note: expected because the closure was earlier called with an argument of type `{integer}`
 --> src/main.rs:3:18
  |
3 |     let a = same(5);
  |             ---- ^ expected because this argument is of type `{integer}`

The first call, same(5), decided that x is an integer. The second call passes a &str, so it’s the wrong type. The note even points at the call that fixed the type.

A closure isn’t generic. It has one parameter type, even if you didn’t write it. If you need a function that works for many types, write a generic fn, as in Part 15.

A closure can use the variables around it

This is what makes a closure more than a short function. A normal fn can’t see the local variables of the function it sits in:

fn main() {
    let name = String::from("Ana");
    fn greet() {
        println!("hello, {name}");
    }
    greet();
}

It prints:

error[E0434]: can't capture dynamic environment in a fn item
 --> src/main.rs:4:27
  |
4 |         println!("hello, {name}");
  |                           ^^^^
  |
  = help: use the `|| { ... }` closure form instead

A closure can:

fn main() {
    let name = String::from("Ana");
    let greet = || println!("hello, {name}");
    greet();
    greet();
    println!("name is still {name}");
}

It prints:

hello, Ana
hello, Ana
name is still Ana

The variables a closure uses from outside are its environment. Using one is called capturing it. greet captures name.

Three ways to capture

A closure can capture a variable in one of three ways:

  1. By shared reference, &, when the body only reads it.
  2. By mutable reference, &mut, when the body changes it.
  3. By value, when the body moves it somewhere. The closure takes ownership.

You don’t choose. The compiler looks at what the body does with each variable and picks the least it needs, in that order. greet above only reads name, so it captures &name. That’s why name still works after greet was made: two shared borrows are fine.

Here are all three at once:

fn main() {
    let name = String::from("Ana");
    let mut count = 0;
    let ticket = String::from("ticket 42");

    let greet = || println!("hello, {name}");
    let mut tick = || count += 1;
    let hand_over = || ticket;

    greet();
    greet();
    tick();
    tick();
    let mine = hand_over();

    println!("{name}, count = {count}, I have {mine}");
}

It prints:

hello, Ana
hello, Ana
Ana, count = 2, I have ticket 42
  • greet reads name, so it captures &name.
  • tick changes count, so it captures &mut count. The closure variable needs mut too, because calling it changes something.
  • hand_over returns ticket. Returning a String moves it out, so the closure must own it. It captures ticket by value, and ticket in main is moved the moment the closure is made.
greet || println!("{name}") tick || count += 1 hand_over || ticket captures &name captures &mut count captures (owns) ticket name "Ana" count 0 ticket moved heap ticket 42 main's variables Fn FnMut FnOnce call it many times many times, needs let mut call it once

What each closure holds. greet borrows name (dashed blue), tick mutably borrows count (dashed red), and hand_over owns the ticket string (solid black), so ticket in main is moved. The bottom row is the trait each closure implements.

In words: greet holds a shared reference to name, and name still has its value. tick holds a mutable reference to count. hand_over holds the String itself, so it owns the heap bytes of “ticket 42”, and main‘s ticket is moved. The arrows are the same ones Part 6 and Part 7 used: dashed blue for &, dashed red for &mut, solid black for an owner.

Explain it like I’m ten

Think of a closure as a note you write for a friend, with a job on it, plus whatever they need to do the job.

If the job is “read the poster on my wall”, you just tell them where the poster is. The poster stays yours, and lots of friends can read it at once. If the job is “add a tick to my scoreboard”, you lend them the scoreboard, and while they have it, nobody else may touch it, not even you. If the job is “post this letter”, you give them the letter. It’s theirs now. They can post it once, and then it’s gone.

The friend can do the first two jobs again and again. The third job can only happen once, because there’s only one letter.

The precise version

The compiler turns each closure into a hidden struct with one field per captured variable. The field is a &T, a &mut T or a T, depending on how the variable is captured. Calling the closure runs a method on that struct. So a closure’s size is the size of what it captures:

fn main() {
    let name = String::from("Ana");
    let mut count = 0;
    let ticket = String::from("ticket 42");

    let add_one = |x: i32| x + 1;
    let greet = || println!("hello, {name}");
    let mut tick = || count += 1;
    let hand_over = || ticket;

    println!("add_one:   {} bytes", size_of_val(&add_one));
    println!("greet:     {} bytes", size_of_val(&greet));
    println!("tick:      {} bytes", size_of_val(&tick));
    println!("hand_over: {} bytes", size_of_val(&hand_over));

    greet();
    tick();
    println!("{} {}", add_one(1), hand_over());
}

It prints:

add_one:   0 bytes
greet:     8 bytes
tick:      8 bytes
hand_over: 24 bytes
hello, Ana
2 ticket 42

On a 64-bit machine, a reference is 8 bytes and a String is 24, as Part 6 showed. add_one captures nothing, so it takes no space at all. Each closure also gets its own type, which has no name you can write. That’s why you’ll see closures passed around with impl Fn and generics, not by their type.

Which trait a closure implements depends on what its body does with the captures:

  • If calling it moves a captured value out, it implements only FnOnce.
  • If calling it changes a captured value, it implements FnMut (and FnOnce).
  • If it only reads, or captures nothing, it implements Fn (and FnMut, and FnOnce).

Where the analogy breaks: the friend is a person who can wander off with your scoreboard. A closure can’t. The compiler checks every borrow a closure holds with the same rules as any other reference, and it does that before the program runs. And the friend decides how to do the job. With a closure, the compiler decides how to capture each variable, from what the body does with it, unless you write move.

Fn, FnMut and FnOnce

Every closure implements at least one of three traits. They’re what you write when you take a closure as a parameter, and they say how often it may be called:

The body Captures Implements You can call it
only reads & Fn, FnMut, FnOnce any number of times
changes something &mut FnMut, FnOnce many times, through let mut
moves something out by value FnOnce once

FnOnce is the “post the letter” closure. Try to call it twice:

fn main() {
    let ticket = String::from("ticket 42");
    let hand_over = || ticket;
    let first = hand_over();
    let second = hand_over();
    println!("{first} {second}");
}

It prints:

error[E0382]: use of moved value: `hand_over`
 --> src/main.rs:5:18
  |
4 |     let first = hand_over();
  |                 ----------- `hand_over` moved due to this call
5 |     let second = hand_over();
  |                  ^^^^^^^^^ value used here after move
  |
note: closure cannot be invoked more than once because it moves the variable `ticket` out of its environment

It’s the same E0382 as Part 6, now about the closure itself. Calling an FnOnce closure consumes it: the call takes the closure by value, so after the first call there’s no closure left. The note gives the reason in plain words: the body moves ticket out.

The borrow rules still apply

Now we can read the “Try this first” error. tick holds &mut count. A mutable borrow lasts until its last use, and the closure’s borrow lasts until the closure’s last call, which was on line 6. In between, println!("{count}") wants a shared borrow of count. “Many readers or one writer” says no.

There are two fixes. The first is to finish with the closure before reading count:

fn main() {
    let mut count = 0;
    let mut tick = || count += 1;
    tick();
    tick();
    println!("{count}");
}

It prints:

2

After the second call, tick is never used again, so its borrow ends there, and println! is free to read. The second fix is to let the closure do the printing, since it already holds the only way in:

fn main() {
    let mut count = 0;
    let mut tick = || {
        count += 1;
        println!("count is now {count}");
    };
    tick();
    tick();
}

It prints:

count is now 1
count is now 2

A closure that captures by & is like any shared borrow, too. You can still read the variable, but you can’t change it or move it while the closure is still to be used.

move closures

Sometimes the compiler’s choice isn’t what you want. A closure that only reads name borrows it, but you may need the closure to own name, because the closure will live longer than the variable. Writing move before the bars forces every capture to be by value:

fn main() {
    let name = String::from("Ana");
    let greet = move || println!("hello, {name}");
    greet();
    greet();
    println!("{name}");
}

It prints:

error[E0382]: borrow of moved value: `name`
 --> src/main.rs:6:16
  |
2 |     let name = String::from("Ana");
  |         ---- move occurs because `name` has type `String`, which does not implement the `Copy` trait
3 |     let greet = move || println!("hello, {name}");
  |                 -------                   ---- variable moved due to use in closure
  |                 |
  |                 value moved into closure here

greet owns name now, so main can’t use it. Notice we called greet twice before the error line, and that part was fine. move changes how the closure captures. It doesn’t change what the body does, and the body only reads, so greet is still Fn. The traits depend on the body, not on move.

For a Copy type like i32, move copies the value into the closure, and the original stays usable:

fn main() {
    let limit = 10;
    let under = move |x: i32| x < limit;
    println!("{} {}", under(3), under(12));
    println!("limit is still {limit}");
}

It prints:

true false
limit is still 10

You’ll need move in two places in this series. One is returning a closure from a function, below. The other is starting a thread in Part 23: a new thread can outlive the function that started it, so the closure you give it must own what it uses.

Passing a closure to a function

A function that takes a closure uses one of the three traits as a bound, just like the bounds in Part 15. You can write it as impl Trait or as a generic. The trait’s brackets list the parameter types, and -> gives the return type:

fn apply(f: impl Fn(i32) -> i32, x: i32) -> i32 {
    f(x)
}

fn repeat<F: FnMut()>(times: u32, mut f: F) {
    for _ in 0..times {
        f();
    }
}

fn run_once<F>(f: F) -> String
where
    F: FnOnce() -> String,
{
    f()
}

fn double(x: i32) -> i32 {
    x * 2
}

fn main() {
    let offset = 100;
    println!("{}", apply(|x| x + offset, 5));
    println!("{}", apply(double, 5));

    let mut log = Vec::new();
    repeat(3, || log.push("tick"));
    println!("{log:?}");

    let ticket = String::from("ticket 42");
    println!("{}", run_once(|| ticket));
}

It prints:

105
10
["tick", "tick", "tick"]
ticket 42

Look at apply(double, 5). A plain function works anywhere a closure is expected, as long as it has the right types. It captures nothing, so it implements all three traits.

In repeat, the parameter is mut f. The function calls f many times, and each call may change what f holds, so f must be mut, the same as tick.

Which bound should a function ask for?

Ask for the least your function needs, because that lets callers pass the most closures:

  • FnOnce if you call it at most once. Every closure qualifies.
  • FnMut if you call it many times, one after another. Closures that read or change qualify.
  • Fn only if you need to call it through a shared reference, for example from several threads at once. Only closures that read qualify.

The standard library follows this rule. Option::unwrap_or_else and Option::map call their closure at most once, so they take FnOnce. Vec::retain and sort_by_key call theirs once per item, so they take FnMut.

If a caller passes a closure that doesn’t qualify, the error names both traits:

fn twice(f: impl Fn()) {
    f();
    f();
}

fn main() {
    let name = String::from("Ana");
    let consume = || {
        let owned = name;
        println!("took {owned}");
    };
    twice(consume);
}

It prints:

error[E0525]: expected a closure that implements the `Fn` trait, but this closure only implements `FnOnce`
  --> src/main.rs:8:19
   |
 8 |     let consume = || {
   |                   ^^ this closure implements `FnOnce`, not `Fn`
 9 |         let owned = name;
   |                     ---- closure is `FnOnce` because it moves the variable `name` out of its environment
...
12 |     twice(consume);
   |     ----- ------- the requirement to implement `Fn` derives from here

Read it top down: the closure only implements FnOnce, line 9 is the reason, and line 12 is where Fn was asked for. The fix depends on what you meant. If consume only needs to read name, borrow it with let owned = &name;. If twice really calls it twice, an FnOnce closure can never fit.

If you write the closure straight into the call instead, the same mistake shows up as E0507, “cannot move out of name, a captured variable in an Fn closure”. Same cause, same fix.

Returning a closure

A function can return a closure with -> impl Fn(...). As Part 15 said, impl Trait in return position means “one specific type that implements this trait”. Each closure has its own type with no name, so impl Fn is how you write it:

fn make_adder(n: i32) -> impl Fn(i32) -> i32 {
    move |x| x + n
}

fn main() {
    let add_five = make_adder(5);
    let add_ten = make_adder(10);
    println!("{} {}", add_five(1), add_ten(1));
}

It prints:

6 11

add_five and add_ten are two closures of the same type, each holding its own copy of n. The move matters, and the next worked example shows what happens without it.

Worked example: a closure that outlives its variables

You want a function that builds a greeting closure for a name. The first try leaves out move:

fn make_greeter(name: String) -> impl Fn() {
    || println!("hello, {name}")
}

fn main() {
    let greet = make_greeter(String::from("Ana"));
    greet();
}

It prints:

error[E0373]: closure may outlive the current function, but it borrows `name`, which is owned by the current function
 --> src/main.rs:2:5
  |
2 |     || println!("hello, {name}")
  |     ^^                   ---- `name` is borrowed here
  |     |
  |     may outlive borrowed value `name`
  |
note: closure is returned here
...
help: to force the closure to take ownership of `name` (and any other referenced variables), use the `move` keyword
  |
2 |     move || println!("hello, {name}")
  |     ++++

Read it in order:

  1. The closure only reads name, so the compiler picked the least: it borrows &name.
  2. name is a parameter of make_greeter, so it’s dropped when make_greeter returns.
  3. The closure is returned, so it lives on after that. Its &name would point at a dropped String. That’s the dangling reference Part 9 was about, and Rust refuses it.
  4. The help: line gives the fix: move, so the closure owns name and takes it along.
fn make_greeter(name: String) -> impl Fn() {
    move || println!("hello, {name}")
}

fn main() {
    let greet = make_greeter(String::from("Ana"));
    greet();
    greet();
}

It prints:

hello, Ana
hello, Ana

The same idea gives you a counter that keeps its own state. The closure owns count, and changes it on each call, so it’s FnMut:

fn make_counter() -> impl FnMut() -> u32 {
    let mut count = 0;
    move || {
        count += 1;
        count
    }
}

fn main() {
    let mut a = make_counter();
    let mut b = make_counter();
    println!("a: {} {} {}", a(), a(), a());
    println!("b: {}", b());
}

It prints:

a: 1 2 3
b: 1

a and b each own a separate count. Nothing outside the closures can see or change it. This is a small piece of state with exactly one way in.

Worked example: sorting and filtering orders

This is where you’ll use closures most: as small arguments to the standard library. Here are the orders from Part 15 again. In Part 15, to say “compare orders by total” we had to implement PartialEq and PartialOrd for Order. With a closure, we say it at the call:

struct Order {
    id: u32,
    customer: String,
    total: u32,
}

fn order(id: u32, customer: &str, total: u32) -> Order {
    Order {
        id,
        customer: customer.to_string(),
        total,
    }
}

fn ids(orders: &[Order]) -> Vec<u32> {
    let mut out = Vec::new();
    for o in orders {
        out.push(o.id);
    }
    out
}

fn main() {
    let mut orders = vec![
        order(1, "Ana", 75),
        order(2, "Ben", 30),
        order(3, "Cai", 120),
        order(4, "Ana", 45),
    ];

    orders.sort_by_key(|o| o.total);
    println!("smallest first: {:?}", ids(&orders));

    orders.sort_by(|a, b| a.customer.cmp(&b.customer).then(b.total.cmp(&a.total)));
    println!("by customer:    {:?}", ids(&orders));

    let min_total = 40;
    let mut too_small = Vec::new();
    orders.retain(|o| {
        if o.total >= min_total {
            true
        } else {
            too_small.push(o.id);
            false
        }
    });
    println!("kept {:?}, removed {:?}", ids(&orders), too_small);

    let wanted = 9;
    let mut found = None;
    for o in &orders {
        if o.id == wanted {
            found = Some(o);
        }
    }
    let who = found
        .map(|o| o.customer.clone())
        .unwrap_or_else(|| format!("no order {wanted}"));
    println!("{who}");
}

It prints:

smallest first: [2, 4, 1, 3]
by customer:    [1, 4, 2, 3]
kept [1, 4, 3], removed [2]
no order 9

order is a small helper that builds an Order, and ids collects the ids so we can print the order of the list.

Here’s what each closure does:

  • sort_by_key(|o| o.total) gets a key from each order, and sorts by the key. The closure is called many times, so sort_by_key takes FnMut.
  • sort_by gets two orders, a and b, and says which comes first. cmp returns Less, Equal or Greater. Here we compare customers first, and then breaks a tie by total. Writing b.total.cmp(&a.total), with a and b swapped, puts the biggest total first. Use sort_by when one key isn’t enough. For a single key in reverse, Clippy suggests sort_by_key(|o| Reverse(o.total)), the Reverse from Part 13.
  • The retain closure captures two things in two ways. It reads min_total, so that’s &min_total. It pushes to too_small, so that’s &mut too_small. A closure picks the capture for each variable on its own.
  • map runs its closure only if there’s a value inside the Option. unwrap_or_else runs its closure only if there isn’t. Both take FnOnce, because each calls its closure at most once.

Why unwrap_or_else and not unwrap_or(format!(...))? unwrap_or takes a ready value, so format! would build the text even when it isn’t needed. The closure builds it only when the Option is empty. Clippy knows this. It warns when you pass a cheap closure like || 0, and suggests unwrap_or(0).

Tips and traps

  • “cannot borrow x as immutable because it is also borrowed as mutable” (E0502) with a closure in the message. A closure that changes x is still going to be called. Finish your calls before you read x, or do the reading inside the closure.
  • “cannot borrow tick as mutable, as it is not declared as mutable” (E0596). The closure changes something it captured, so calling it changes the closure. Write let mut tick = ..., and in a function, take mut f: F.
  • “closure may outlive the current function” (E0373). You’re returning the closure, or giving it to a thread. Add move, as the help: line says.
  • move doesn’t make a closure FnOnce. The trait comes from what the body does. A move closure that only reads is still Fn and can be called many times.
  • Asking for Fn when you mean FnMut or FnOnce. It shuts out closures that change or consume things, and callers get E0525. Ask for the least your function needs.
  • unwrap_or(expensive()) builds the value every time. Use unwrap_or_else(|| expensive()) when the default costs something. For a plain value like 0, keep unwrap_or.

A closure borrows what it reads, mutably borrows what it changes, and owns what it gives away, and that choice decides whether it is Fn, FnMut or FnOnce.

Exercises

Exercise 1. Without running it, say which of Fn, FnMut and FnOnce each closure implements. List all that apply.

let mut list = vec![1, 2, 3];
let double = |x: i32| x * 2;
let mut add_four = || list.push(4);
let take_list = || list;

Exercise 2. Write a function make_multiplier(n: i32) that returns a closure, so that make_multiplier(3)(7) is 21.

Exercise 3. This program doesn’t compile. Fix it by deleting one word, and explain why that works.

fn main() {
    let name = String::from("Ana");
    let greet = move || println!("hello, {name}");
    greet();
    println!("bye, {name}");
}

It prints:

error[E0382]: borrow of moved value: `name`
Answers

1. double captures nothing, so it implements all three. add_four changes list, so it implements FnMut and FnOnce. take_list returns list, which moves it out, so it implements only FnOnce. Note that the three can’t all be alive at once: add_four mutably borrows list, and take_list moves it. This program proves the traits by passing each closure to a function that asks for exactly one trait. It finishes with add_four before it makes take_list:

fn needs_fn(f: impl Fn(i32) -> i32) -> i32 {
    f(1)
}

fn needs_fn_mut(mut f: impl FnMut()) {
    f();
}

fn needs_fn_once(f: impl FnOnce() -> Vec<i32>) -> Vec<i32> {
    f()
}

fn main() {
    let mut list = vec![1, 2, 3];
    let double = |x: i32| x * 2;
    let add_four = || list.push(4);

    println!("{}", needs_fn(double));
    needs_fn_mut(add_four);

    let take_list = || list;
    println!("{:?}", needs_fn_once(take_list));
}

It prints:

2
[1, 2, 3, 4]

add_four doesn’t need let mut here, because we never call it in main. needs_fn_mut takes it as mut f and calls it there.

2. The closure must own n, because n is dropped when make_multiplier returns. So it needs move:

fn make_multiplier(n: i32) -> impl Fn(i32) -> i32 {
    move |x| x * n
}

fn main() {
    let triple = make_multiplier(3);
    println!("{}", triple(7));
    println!("{}", make_multiplier(3)(7));
}

It prints:

21
21

3. Delete move. Without it, the closure only reads name, so the compiler captures &name. That’s a shared borrow, and println! can read name too. With move, the closure owned name, so main had nothing left to print.

fn main() {
    let name = String::from("Ana");
    let greet = || println!("hello, {name}");
    greet();
    println!("bye, {name}");
}

It prints:

hello, Ana
bye, Ana

What’s next

Closures are half of what makes Rust’s iterators work. In Part 17, we’ll build lazy pipelines with map, filter and collect, and see what happens when each item is pulled through them one at a time.

How useful was this post?

Click on a heart to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.