Rust Playbook

Course › Week 3 · Iterators, real data, speed › Day 1 · lesson 15 of 42 · 15 min reading + 45–60 min practice

Closures

Functions you can store and pass, and what they capture.

closuresFnFnMutFnOncemove

On this page
  1. 1. A closure is a function you can store
  2. 2. A closure can use the variables around it
  3. 3. Passing a closure to a function
  4. 4. FnMut: a closure that changes what it captured
  5. 5. move: the closure takes ownership
  6. 6. FnOnce: a closure that can only run once
  7. 7. Where you have already used them
  8. Coming from PHP
  9. Practice
  10. Remember

You have already used closures without their own lesson: |a, b| b.1.cmp(&a.1) in sort_by, |source| LogError::Open { … } in map_err. Today they get the slow treatment, because this whole week is built on them: iterators take closures, serde does not, and rayon runs your closures on every core.

A closure is a function without a name, written inline, that can use variables from the place it was written. PHP has the same idea twice: function () use ($x) { … } and fn () => ….

1. A closure is a function you can store

Parameters go between pipes, then the body. For a one-line body, no braces are needed. The types can be written, or left for the compiler to infer from how the closure is used.

src/main.rs
fn main() {
    let is_long_stay = |nights: u32| nights >= 7;
    let nightly_total = |nights: u32, cents: u64| -> u64 { u64::from(nights) * cents };

    println!("{}", is_long_stay(3));
    println!("{}", is_long_stay(9));
    println!("{}", nightly_total(3, 15_010));
}
$ cargo run
false
true
45030

Called exactly like a function. The difference from fn is not the syntax; it is the next section.

2. A closure can use the variables around it

A fn cannot see the local variables of the function it is written in. A closure can, and captures them: here, minimum is read inside the closure without being passed in.

src/main.rs
fn main() {
    let minimum: u32 = 3; // could come from the property's settings

    let allowed = |nights: u32| nights >= minimum;

    for nights in [1, 3, 7] {
        println!("{nights} nights allowed: {}", allowed(nights));
    }
}
$ cargo run
1 nights allowed: false
3 nights allowed: true
7 nights allowed: true

By default a closure captures the least it needs: here only a borrow of minimum, because it only reads it. All the Day 4 rules apply to that borrow: while the closure exists and may still be called, nobody can change minimum.

3. Passing a closure to a function

A function that accepts a closure names the shape it expects with a trait: impl Fn(u32) -> bool means “something I can call with a u32 that gives back a bool”. It is Week 2’s impl Trait; Fn is a trait the compiler implements for every closure that fits.

src/main.rs
fn count_where(stays: &[u32], keep: impl Fn(u32) -> bool) -> usize {
    let mut count = 0;
    for &nights in stays {
        if keep(nights) {
            count += 1;
        }
    }
    count
}

fn main() {
    let stays: Vec<u32> = vec![2, 7, 3, 14, 1, 9];
    let minimum: u32 = 7;

    println!("long stays:  {}", count_where(&stays, |n| n >= minimum));
    println!("one night:   {}", count_where(&stays, |n| n == 1));
}
$ cargo run
long stays:  3
one night:   1

for &nights in stays takes each &u32 apart into a plain u32, the & on the left undoing the reference on the right. It works because u32 is Copy.

This is what iterator methods like filter do, tomorrow: they take your closure and call it for each item.

4. FnMut: a closure that changes what it captured

A closure that changes a captured variable borrows it mutably. Two things follow: the closure variable itself must be mut, because calling it changes state, and a function that accepts it must ask for FnMut instead of Fn.

src/main.rs
fn for_each_line(lines: &[&str], mut handle: impl FnMut(&str)) {
    for line in lines {
        handle(line);
    }
}

fn main() {
    let lines = [
        "[2026-11-30 09:41:03] production.ERROR: Deadlock found",
        "#0 /var/www/app/Actions/ConfirmBooking.php(41)",
        "[2026-11-30 09:41:04] production.INFO: Booking confirmed",
    ];

    let mut errors: u32 = 0;
    for_each_line(&lines, |line| {
        if line.contains(".ERROR:") {
            errors += 1;
        }
    });

    println!("{errors} errors");
}
$ cargo run
1 errors

The three closure traits, from most to least permissive for the caller:

TraitThe closure…Can be called
Fnonly reads what it capturedany number of times, even from several places at once
FnMutchanges what it capturedany number of times, one call at a time
FnOncegives away something it captured (section 6)once

You almost never write these by hand on a closure. The compiler decides which ones a closure implements from what its body does; you only name them in a function signature, to say what you accept.

5. move: the closure takes ownership

Returning a closure from a function is how you build a rule from settings. But this one borrows minimum, a variable that dies when the function returns:

src/main.rsdoes not compile
fn at_least(minimum: u32) -> impl Fn(u32) -> bool {
    |nights| nights >= minimum
}

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

For more information about this error, try `rustc --explain E0373`.
error: could not compile `hello` (bin "hello") due to 1 previous error

The compiler’s fix is one word: move. A move closure takes ownership of everything it captures (here, a copy of the u32), so it no longer depends on the function’s variables.

src/main.rs
fn at_least(minimum: u32) -> impl Fn(u32) -> bool {
    move |nights| nights >= minimum
}

fn main() {
    let weekend_rule = at_least(2);
    let summer_rule = at_least(7);

    println!("2 nights, weekend: {}", weekend_rule(2));
    println!("2 nights, summer:  {}", summer_rule(2));
}
$ cargo run
2 nights, weekend: true
2 nights, summer:  false

You will write move on Day 5, for closures sent to other threads, and in Week 4, for async tasks. Same reason both times: the closure must outlive the place it was made.

6. FnOnce: a closure that can only run once

This closure moves report, a String it owns, into a function. After the first call it no longer has it, so a second call cannot work:

src/main.rsdoes not compile
fn send(message: String) {
    println!("sent: {message}");
}

fn main() {
    let report = String::from("3 errors since 08:00");
    let send_report = move || send(report);

    send_report();
    send_report();
}
cargo build
error[E0382]: use of moved value: `send_report`
  --> src/main.rs:10:5
   |
 9 |     send_report();
   |     ------------- `send_report` moved due to this call
10 |     send_report();
   |     ^^^^^^^^^^^ value used here after move
   |
note: closure cannot be invoked more than once because it moves the variable `report` out of its environment
  --> src/main.rs:7:36
   |
 7 |     let send_report = move || send(report);
   |                                    ^^^^^^
note: this value implements `FnOnce`, which causes it to be moved when called
  --> src/main.rs:9:5
   |
 9 |     send_report();
   |     ^^^^^^^^^^^

For more information about this error, try `rustc --explain E0382`.
error: could not compile `hello` (bin "hello") due to 1 previous error

This is Day 3’s move, through a closure. The compiler says the closure is FnOnce because of where it moves report. Call it once, or have send borrow &str so the closure only needs to read.

7. Where you have already used them

CallThe closureCalled
ranked.sort_by(|a, b| b.1.cmp(&a.1))compares two itemsmany times while sorting
.map_err(|source| LogError::Open { … })builds your error from the originalonly if there is an error
value.unwrap_or_else(|| default())computes a defaultonly if the value is missing

|| … with nothing between the pipes is a closure with no parameters. unwrap_or_else takes one instead of a value so the default is only computed when it is needed, unlike unwrap_or(value), whose argument is always computed first.

Coming from PHP

PHP closures capture by value, and only what you list in use. Arrow functions capture everything they use, also by value:

closures.php
<?php

$minimum = 3;
$allowed = fn (int $nights): bool => $nights >= $minimum;   // a copy of $minimum

$errors = 0;
$count = function (string $line) use (&$errors): void {        // & needed to change it
    if (str_contains($line, '.ERROR:')) {
        $errors++;
    }
};

Rust captures by borrow unless you say move, and it checks every capture like any other borrow: a closure that changes errors blocks everyone else from touching it until the closure is done. PHP’s use (&$errors) has no such check.

PracticeThe Book ch. 13.1, and one function that takes a rule

Read chapter 13.1 of the Book. Rustlings has no closure folder; its 18_iterators tomorrow uses them throughout.

Exercise: a price rule from settings

Write fn discount(percent: u64, from_nights: u32) -> impl Fn(u64, u32) -> u64 that returns a closure taking a total in cents and a number of nights, and returning the total minus percent percent when the stay is at least from_nights long. Build a weekly rule (10% from 7 nights) and a monthly rule (25% from 28 nights), and apply both to 45,030 cents for 3, 7 and 28 nights. Integers only: take off total * percent / 100.

Show the solution
src/main.rs
fn discount(percent: u64, from_nights: u32) -> impl Fn(u64, u32) -> u64 {
    move |total, nights| {
        if nights >= from_nights {
            total - total * percent / 100
        } else {
            total
        }
    }
}

fn main() {
    let weekly = discount(10, 7);
    let monthly = discount(25, 28);

    for nights in [3, 7, 28] {
        println!(
            "{nights:>2} nights: weekly {}, monthly {}",
            weekly(45_030, nights),
            monthly(45_030, nights)
        );
    }
}
$ cargo run
 3 nights: weekly 45030, monthly 45030
 7 nights: weekly 40527, monthly 45030
28 nights: weekly 40527, monthly 33773

move copies percent and from_nights into each closure, so weekly and monthly each keep their own settings.

Remember

  • A closure borrows what it uses unless it is move; use move when it must outlive the place it was made.
  • Accept closures with impl Fn, impl FnMut or impl FnOnce, the loosest your function can work with.

Tomorrow: iterators. map, filter, collect and friends, each one taking a closure.