Closures

Closures in Rust: A recipe in a book is complete. It names its own ingredients, it works in any kitchen, and you can photocopy it and post it abroad and it…

The Analogy: The Instruction Taped To The Machine

A recipe in a book is complete. It names its own ingredients, it works in any kitchen, and you can photocopy it and post it abroad and it still means exactly what it meant. Nothing about it depends on where the book happens to be sitting.

The card taped to the side of a machine is not like that. It says "when the light comes on, top up from the drum behind you", and the drum is part of the instruction even though the drum is not written on the card. Take the card to another building and it becomes nonsense. That is not a defect. The card is short and useful because it can point at the room it lives in.

There are three relationships the card can have with that drum, and the difference matters. It can read the gauge on the side, in which case anyone else may read it too. It can draw fuel from it, in which case nobody else may touch it while the card is being followed. Or it can say "use up what remains and take the drum for scrap", in which case the instruction can be carried out exactly once, and after that there is no drum. The first two can be followed all afternoon; the third is a one-off by its nature.

And when the card has to travel -- posted to another site, or handed to a night shift that starts after you have gone home and locked the room -- reading the gauge is no longer good enough. Whatever the card points at has to go with it. That is not the card changing what it does; it is the card taking possession of what it needs so that it stops depending on a room it will never see again.


Syntax or Core Structure

A closure is written between vertical bars and can see the variables around it:

fn main() {
    let vat = 20;

    let with_vat = |pence: u32| pence + pence * vat / 100;

    println!("{}", with_vat(1000));
    println!("{}", with_vat(499));

    let double = |n: u32| -> u32 { n * 2 };

    println!("{}", double(21));

    let greet = || println!("bay ready");

    greet();
    greet();
}

Output:

1200
598
42
bay ready
bay ready

The second number is worth a second look: 499 * 20 is 9980, and 9980 / 100 is 99 in integer division, so the answer is 598 rather than 598.8 rounded. Nothing to do with closures, everything to do with reading your own output.

The whole point is the line that is not there. with_vat never received vat as an argument and never declared it. Write the same body as a function and it does not compile:

fn with_vat(pence: u32) -> u32 {
    pence + pence * vat / 100
}

That is error[E0425]: cannot find value vat in this scope. A function item sees only its parameters, its own locals, and things that are global; it has no surroundings. A closure has surroundings, and capturing them is the one thing it can do that a function cannot.

A fn itemA closure
Sees the variables around itNoYes
Parameter and return typesAlways written outUsually inferred
Has a nameAlwaysOnly if you bind it to one
Its typefn(u32) -> u32, shared by every function with that shapeAnonymous, and unique to that one closure
Stored in a struct fieldDirectly, as a function pointerNeeds a generic parameter or a box

Types are inferred from use, which is why |pence: u32| above could have been written |pence| and still compiled: the calls fix it. Inference happens once, though. A closure written let same = |x| x; and then called with a number is a closure over numbers forever, and calling it with a string afterwards is a type error, not a second inference.


Technical Depth: What A Closure Captures, And What It Costs

The three ways in

fn main() {
    let bay = String::from("bay 3");
    let show = || println!("at {bay}");

    show();
    println!("still usable: {bay}");

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

    tick();
    tick();
    println!("total {count}");

    let label = String::from("crate 9");
    let consume = move || {
        let owned = label;
        println!("consumed {} bytes", owned.len());
    };

    consume();
}

Output:

at bay 3
still usable: bay 3
tick 1
tick 2
total 2
consumed 7 bytes

Three closures, three different relationships with what they captured. show only reads bay, so it takes a shared borrow and bay is still usable on the next line. tick assigns to count, so it takes a mutable borrow -- which is why the binding itself has to be let mut tick, a detail that catches almost everyone once. And reading count after the last tick() works because the closure's borrow ends at its final use, not at the end of the block.

consume moves label out of itself. That is the one-off case: the closure can be called once, and label is unusable both inside the closure a second time and outside it at all.

What the body does with a captured variableCaptured byTraits it getsTimes callable
Reads itShared borrowFn, FnMut, FnOnceAny number
Assigns to or mutates itMutable borrowFnMut, FnOnceAny number, via a mut binding
Moves it out or consumes itBy valueFnOnce onlyExactly once

Every closure implements FnOnce. A closure that only borrows implements all three, which is why the traits form a ladder rather than three separate boxes: Fn is the strongest promise and FnOnce the weakest.

What move does and does not do

fn main() {
    let name = String::from("north");
    let show = move || println!("{name}");

    show();
    show();
}

Output:

north
north

move forces every capture to be taken by value regardless of what the body does with it, and it is the reason name cannot be used after this point. What it does not do is make the closure FnOnce. This closure owns a String and only reads it, so it is still Fn and still callable twice. The two questions are independent: move decides how the values got in, and the body decides how many times the closure can run.

Accepting a closure as an argument

fn apply_twice<F: Fn(u32) -> u32>(f: F, start: u32) -> u32 {
    f(f(start))
}

fn tally<F: FnMut(u32)>(mut f: F, upto: u32) {
    for n in 1..=upto {
        f(n);
    }
}

fn once<F: FnOnce() -> String>(f: F) -> String {
    f()
}

fn main() {
    println!("{}", apply_twice(|n| n + 3, 10));

    let mut total = 0;
    tally(|n| total += n, 5);
    println!("total {total}");

    let held = String::from("dispatch note");
    println!("{}", once(move || held));
}

Output:

16
total 15
dispatch note

Note mut f: F in tally. Calling an FnMut needs a mutable place to call it from, and since tally owns f, it is tally that declares the mut -- the caller's closure is passed as a plain expression.

BoundChoose it when
FnThe closure only reads, and you may call it many times or from several places
FnMutUpdating something as it goes is the closure's job, and you call it repeatedly from one place
FnOnceYou call it at most once, or it hands over ownership of something

The rule for picking one runs opposite to intuition: ask for the weakest trait your body actually needs. FnOnce accepts every closure in the language, FnMut accepts all but the consuming ones, and Fn accepts the fewest. A parameter declared Fn when the code only ever calls it once has turned a loose requirement into a needless restriction, and the caller pays for it.

Every closure is its own type

fn main() {
    let a = |n: u32| n + 1;
    let b = |n: u32| n + 1;

    println!("{} {}", a(1), b(1));

    let fns: [fn(u32) -> u32; 2] = [|n| n + 1, |n| n * 2];

    for f in fns {
        println!("{}", f(10));
    }
}

Output:

2 2
11
20

a and b have identical bodies and identical signatures and are still different types, so vec![a, b] is error[E0308]: mismatched types. The array works because a closure that captures nothing coerces to a plain function pointer, and fn(u32) -> u32 is one type that both can become. As soon as one of them captures, that escape route closes, and holding several different capturing closures in one collection needs a boxed trait object -- Module 8.

Handing a closure back

fn adder(step: u32) -> impl Fn(u32) -> u32 {
    move |n| n + step
}

fn main() {
    let plus5 = adder(5);
    let plus100 = adder(100);

    println!("{} {}", plus5(1), plus100(1));
}

Output:

6 101

The move is not decoration here. Without it the closure would borrow step, which is a local of adder, and returning it would be error[E0373]: the closure would outlive the value it points at. This is the analogy's fourth paragraph in compiler form -- the card is leaving the room, so it has to take the drum. And as Module 6 established, impl Fn in return position means exactly one concrete type, so a function that returns one closure on one branch and a different one on another needs a box instead.


Real World Example: One Billing Loop, Four Different Tariffs

A charging routine that knows how to walk a list of sessions and add up money, and knows nothing whatsoever about how money is calculated. Both of those jobs arrive as closures.

struct Session {
    id: &'static str,
    minutes: u32,
    peak: bool,
}

fn bill<T, A>(sessions: &[Session], tariff: T, mut audit: A) -> u32
where
    T: Fn(&Session) -> u32,
    A: FnMut(&'static str, u32),
{
    let mut total = 0;

    for s in sessions {
        let charge = tariff(s);

        total += charge;
        audit(s.id, charge);
    }

    total
}

fn tariff_for(base: u32, surcharge: u32) -> impl Fn(&Session) -> u32 {
    move |s| {
        let extra = if s.peak { surcharge } else { 0 };

        s.minutes * (base + extra)
    }
}

fn main() {
    let sessions = [
        Session { id: "s-01", minutes: 12, peak: false },
        Session { id: "s-02", minutes: 45, peak: true },
        Session { id: "s-03", minutes: 3, peak: false },
        Session { id: "s-04", minutes: 90, peak: true },
    ];

    let flat_rate = 4;
    let peak_rate = 7;

    let flat = |s: &Session| s.minutes * flat_rate;

    let tiered = |s: &Session| {
        let rate = if s.peak { peak_rate } else { flat_rate };
        let capped = if s.minutes > 60 { 60 } else { s.minutes };

        capped * rate
    };

    let mut log: Vec<String> = Vec::new();
    let flat_total = bill(&sessions, flat, |id, pence| {
        log.push(format!("{id} {pence}"));
    });

    println!("flat    {flat_total}");

    for line in &log {
        println!("  {line}");
    }

    let mut biggest = ("", 0);
    let tiered_total = bill(&sessions, tiered, |id, pence| {
        if pence > biggest.1 {
            biggest = (id, pence);
        }
    });

    println!("tiered  {tiered_total}");
    println!("  worst {} at {}", biggest.0, biggest.1);

    let weekend = tariff_for(3, 1);
    let weekday = tariff_for(5, 4);

    println!("weekend {}", bill(&sessions, weekend, |_, _| {}));
    println!("weekday {}", bill(&sessions, weekday, |_, _| {}));
}

Output:

flat    600
  s-01 48
  s-02 180
  s-03 12
  s-04 360
tiered  795
  worst s-04 at 420
weekend 585
weekday 1290

bill is fourteen lines long and there is exactly one of it. Four tariffs went through it -- a flat rate, a tiered rate with a cap, and two built at run time by tariff_for -- and none of them required the loop to change, gain a parameter, or learn a new word. That is the ordinary payoff, and the interesting part is why a function pointer could not have done the same job. flat uses flat_rate, which is a value in main. A fn(&Session) -> u32 has nowhere to put it. Had the rate come from a config file read at startup rather than a literal, the function-pointer version would have had to reach for a global or thread the rate through every signature; the closure carries it and the signature never hears about it.

The two bounds are deliberately different. tariff is Fn because it is asked the same question once per session and must give the same answer regardless of order -- a tariff that accumulated state between sessions would be a pricing bug, and the bound is where that intention is written down. audit is FnMut because accumulating is its entire purpose, and the same bill accepted two completely unrelated accumulators: one that pushes formatted lines onto a Vec<String>, and one that keeps a running maximum in a tuple. The third and fourth calls pass |_, _| {}, which accumulates nothing at all and satisfies FnMut because every closure does.

There is a lifetime in that signature doing real work. A: FnMut(&'static str, u32) says the id handed to the callback lives forever, which is what makes biggest = (id, pence) legal -- the tuple outlives the call it came from. Write the bound as FnMut(&str, u32) instead and the callback becomes higher-ranked over some short anonymous lifetime, and that same assignment stops compiling, because nothing then promises the id survives past one call. It works here because Session::id genuinely is a &'static str. For a program that read its sessions out of a file, the ids would not be static, the bound would have to be FnMut(&str, u32), and a callback wanting to keep one would call to_string() on it. Module 6's lifetimes are not a separate topic from this one; they are the reason this signature has a choice to make.

The limits are the usual mix of the small and the structural. Every figure is u32 pence, so a long enough session list overflows -- silently in a release build, as the previous lesson's --release note explains. The 60-minute cap inside tiered is a real business rule living in an anonymous closure with no name, no doc comment and no test, which is the standard way closures get abused: they are so cheap to write that rules end up hidden in them. bill also makes one pass per tariff, so the four calls walk the same four sessions four times, which is free here and would not be over a million rows. Passing the same closure to bill twice happens to work for flat, since its only capture is a borrow of a u32 and that makes the closure Copy; a closure that owned a String would be moved by the first call and rejected by the second. And the design holds exactly one tariff at a time -- a price book of twenty named tariffs sitting side by side needs a boxed trait object or an enum, which is Module 8.


Common Mistakes

  1. Forgetting mut on the binding of a closure that mutates. A closure that assigns to something it captured is FnMut, and calling it needs a mutable place, so let tick = || { count += 1; }; followed by tick() is error[E0596]: cannot borrow tick as mutable. The fix is let mut tick, and the confusing part is that the mut goes on the closure, not on what the closure changes -- that one needs mut too, separately.
  1. Using a variable after a move closure took it. Once move has pulled a String in, the original binding is gone, and the next mention of it is error[E0382]: borrow of moved value. The message points at the later line, but the cause is the move keyword several lines above it, which is worth remembering when the error looks like it is about the wrong statement.
  1. Calling a closure stored in a field without parentheses. If a struct has a field holding a closure, self.tariff(s) does not call it -- Rust reads that as a method named tariff on the struct and reports that no such method exists. The call is (self.tariff)(s), and the extra brackets are not optional style.
  1. Asking for Fn when the body needs FnMut. A parameter bound F: Fn(u32) rejects any closure that accumulates, with a message about a closure implementing FnMut where Fn was expected. This is not the caller's mistake; it is a bound that was written tighter than the function actually required.
  1. Expecting two closures with the same shape to be the same type. They are not, ever, no matter how identical the bodies look, so vec![a, b] fails with a type mismatch. Non-capturing closures can be coerced to fn pointers and collected that way, and capturing ones need a box.
  1. Returning a closure that borrows a local, without move. The closure compiles happily inside the function and dies at the return with error[E0373], because a borrow of a local cannot leave the function that owns it. Anything a closure needs after its birthplace has gone must be owned by the closure.
  1. Reading move as "this closure can only run once". It is not what it means. move decides how the captures got in, and the body decides how many times the closure may run, so a move closure that only prints an owned String is a perfectly ordinary Fn you can call all day.
  1. Expecting a closure's parameter types to be re-inferred at each call. They are inferred once, from the first use that pins them down. let same = |x| x; used on a number is a number-to-number closure permanently, and passing a string to it later is a type error rather than a second inference.
  1. Reading a captured variable while the closure over it is still alive. An FnMut closure holds a mutable borrow for as long as it might still be called, so printing count in between two tick() calls is error[E0502]. Reading it after the last call is fine, which makes the rule feel arbitrary until you notice that the borrow ends at the closure's final use.

Best Practices

  • Let inference do the work. Write |s: &Session| when a bound needs pinning or the reader needs the hint, and plain |s| the rest of the time -- an annotation on every closure parameter is noise that hides the ones that mattered.
  • Bound your parameters with the weakest trait the body needs: FnOnce if you call it once, FnMut if you call it repeatedly, Fn only when several callers might use it at the same time. Every step tighter than necessary rejects callers for no benefit.
  • Reach for move whenever the closure will outlive the scope it was written in -- returned, stored, or handed to another thread. Treating it as the default for those three cases saves a round trip through E0373.
  • Bind a closure to a let with a real name when it encodes a decision. let over_cap = ... in front of a call site is documentation that costs one line and survives refactoring.
  • Keep the body short. A closure that has grown past a handful of lines, or that wants a doc comment, or that you would like to test on its own, is a function wearing the wrong clothes.
  • Prefer a generic parameter over a boxed trait object while the closure is only being passed in. Generics monomorphise and inline; boxing is the tool for storing several unrelated closures together, not for accepting one.
  • Do not let a business rule hide in an anonymous closure. If the number 60 means something to your accountants, it belongs in a named function or constant that a test can point at, and the closure can call it.
  • Use plain fn pointers when nothing is captured. An array of fn(u32) -> u32 is simpler to read, simpler to store and simpler to name than a generic parameter you introduced for no reason.

Practice Exercises

  1. Write apply_n<F>(mut f: F, start: u32, times: u32) -> u32 that applies f repeatedly, and call it with a closure that both doubles its input and counts how many times it was asked. Show the exact error you get if the bound is written Fn instead of FnMut, and explain in one sentence which of the two jobs the closure is doing caused it.
  1. Add a third parameter to bill bounded FnOnce() -> String that is called once after the loop and whose result is printed. Pass a closure that takes ownership of a String from main, then try to call the parameter twice inside bill and record what the compiler says about why it cannot.
  1. Write fn stepper(start: u32, by: u32) -> impl FnMut() -> u32 that returns the running value each time it is called, and call it four times from main. Say for each of start and by whether it is captured by borrow or by value and why the returned closure is FnMut rather than Fn.
  1. Change the audit bound in the billing example from FnMut(&'static str, u32) to FnMut(&str, u32) and watch the biggest closure stop compiling. Fix it twice: once by storing id.to_string(), and once by putting 'static back. Then change Session::id to a String and work out which of the two fixes is still available to you.