Skip to content
Tutorials Center
My learning

Topics

Lesson 54 of 132 ยท Collections and Iterators

Closures

Understand Rust closures - syntax, capturing by borrow, mutable borrow or move, the Fn, FnMut and FnOnce traits, passing and returning closures, boxing them, and async closures.

A closure is a small anonymous function that can use variables from the place where it was written. You have already seen them as the |n| n * 2 arguments to map and filter. They are Rust's answer to JavaScript arrow functions, Python lambdas and C++ lambdas, with one important twist: the compiler tracks exactly how each closure uses the variables around it, and that decides what you are allowed to do with the closure afterwards.

If you understand that one idea (a closure captures its surroundings by borrowing, mutably borrowing or moving, and the way it uses them gives it one of three traits), the rest of this lesson is details. We start with syntax, then capturing, then the traits Fn, FnMut and FnOnce, and finally how to accept, return and store closures.

Closure syntax

A closure is written with vertical bars around its parameters, followed by the body. Types are usually inferred, and a single expression needs no braces.

Rust Closure syntax from long to short

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Closure parameter and return types are inferred from the first use and then fixed. A closure like |x| x called once with an i32 and again with a String does not compile: it is one concrete function, not a generic one.

Rust A closure has one inferred type (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

You get error[E0308]: mismatched types pointing at the String::from("five") argument, with the note "expected integer, found String". If you need a closure that works on several types, write a generic function instead.

Capturing: borrow, mutate or move

What makes a closure different from a plain fn is that it can use local variables from the enclosing scope. Rust picks the least demanding way of capturing each variable that the body allows:

  1. Shared borrow (&T) if the body only reads it.
  2. Mutable borrow (&mut T) if the body changes it.
  3. Move (by value) if the body consumes it, for example by passing it to a function that takes ownership or returning it.
Rust Three ways to capture

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

In case 2, the line println!("final count: {count}") works because bump is never used afterwards: the mutable borrow ended after its last use. That is the same borrowing rule as everywhere else, in the "non-lexical" style from non-lexical lifetimes.

The move keyword

The move keyword before the bars forces every captured variable to be moved (or copied, for Copy types) into the closure. You need it when the closure must outlive the place it was created: returned from a function, or sent to another thread.

Rust move keyword

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

move changes how a variable is captured, not what the closure does. A closure declared move that only reads the value is still Fn (see below). Threads, covered in Concurrency, are the most common reason to write move.

The three closure traits

Every closure automatically implements one, two or all three of these traits, depending on what its body does to the captured values:

Trait Call needs The closure body... Callable
FnOnce self may move captured values out at least once; all closures are FnOnce
FnMut &mut self may mutate captured values many times
Fn &self only reads captured values many times, even at once

They form a hierarchy: every Fn is also FnMut, and every FnMut is also FnOnce. A function that accepts FnOnce is the most permissive (it takes any closure), and one that demands Fn is the most restrictive.

Rust Which trait does a function ask for?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

When you write your own function, choose the weakest bound that works: FnOnce if you call it once, FnMut if you call it repeatedly but may allow mutation, and Fn only if you need to call it from several places at the same time (for example, sharing it between threads). Asking for Fn when FnMut would do needlessly rejects closures that count or collect things.

If you pass a closure that is too "strong" for the bound, rustc tells you which trait it implements:

Rust A FnOnce closure where Fn is expected (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The error is error[E0507]: cannot move out of `message`, a captured variable in an `Fn` closure. The fix is to change the bound to FnOnce (and call it once), or to stop moving the value out of the closure (clone it, or just borrow it).

Closures as parameters: generics versus dyn

There are two ways to accept a closure. A generic parameter (F: Fn(i32) -> i32, or the shorthand impl Fn(i32) -> i32) is compiled separately for each closure type and called directly, so it is as fast as inlined code. A trait object (&dyn Fn(i32) -> i32) uses one compiled function and a dynamic call.

Rust Generic, impl and dyn parameters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Passing the name of a function (map(double), map(Some), map(String::from)) instead of |x| double(x) is idiomatic when the closure would only forward its argument. Non-capturing closures can also be converted into plain function pointers (fn(i32) -> i32).

Returning and storing closures

Every closure has its own unique, unnameable type, so you cannot write that type in a signature. You have two options.

  • impl Fn(...) in return position when you return exactly one closure (as make_greeter did).
  • Box<dyn Fn(...)> when the closure type varies at run time or you need to store different closures together.
Rust Boxed closures in a collection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Each Box<dyn Fn> costs a heap allocation and a pointer-indirect call. That is perfectly fine for callbacks and command tables, but prefer generics in hot inner loops. Note that the move closure that increments counter modifies its own copy; the outer counter stays 0.

Closures in iterator chains

Most closures you write will be iterator arguments, as in the iterators lessons. They capture local variables naturally, which makes configurable pipelines easy:

Rust Closures capturing context in a pipeline

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Async closures (preview)

Rust 1.85 stabilised async closures, written async |x| { ... }. They are closures that return a future and, unlike the older |x| async move { ... } trick, may let the future borrow from the closure's captured state. They use the new AsyncFn, AsyncFnMut and AsyncFnOnce traits. You need an async runtime to run them, which this browser runner does not provide, so here is a read-only preview. The Async Rust chapter covers the background.

Rust
// Read-only: needs an async executor, so it is not runnable here.
async fn run_all(urls: &[String], fetch: impl AsyncFn(&str) -> usize) -> usize {
    let mut total = 0;
    for url in urls {
        total += fetch(url).await;
    }
    total
}

Pitfalls and design notes

  • Closures borrowing locals cannot be returned without move. The error says closure may outlive the current function, but it borrows ..., and help suggests move.
  • A mut closure variable is required to call an FnMut closure through a binding: let mut bump = || count += 1;.
  • Do not capture more than you need. A closure that mentions self.name in edition 2021+ captures only that field, not all of self, so other fields stay usable.
  • Cloning inside closures (.clone() in a move closure) is the normal way to give each closure its own copy, for example one Arc clone per thread.
  • Recursion: a closure cannot call itself directly. Use a nested fn or pass the closure to itself explicitly.
  • Size: a non-capturing closure is zero-sized; a capturing one is as large as its captures.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A closure only reads a captured String. How does it capture it by default?

    Rust captures with the least demanding mode that the body allows. Only reading needs a shared borrow; mutating needs &mut; consuming needs a move.
  2. 2. Which trait does a closure implement if its body moves a captured variable out (for example returns it)?

    Moving a captured value out can happen only once, so the closure is FnOnce but not FnMut or Fn.
  3. 3. Why do you need move on a closure returned from a function that uses a local variable?

    Without move the closure borrows the local, which dies at the end of the function. move transfers ownership into the closure.
  4. 4. How do you declare a variable holding a closure that mutates captured state so you can call it?

    Calling an FnMut closure needs &mut access to the closure value itself, so the binding must be mut.
  5. 5. When must you use Box<dyn Fn(i32) -> i32> instead of impl Fn(i32) -> i32?

    impl Fn stands for one concrete closure type. A Vec of different closures, or a function returning different closures per branch, needs trait objects.

Summary

  • Closures are written |args| body; parameter and return types are inferred from the first use and then fixed.
  • They capture by shared borrow, mutable borrow or move, choosing the least demanding mode the body allows; move forces ownership.
  • Fn (reads), FnMut (mutates, needs mut binding) and FnOnce (may consume) form a hierarchy; ask for the weakest bound that works.
  • Accept closures with generics or impl Fn for speed, &dyn Fn for one shared compiled copy.
  • Return impl Fn for a single closure, Box<dyn Fn> for varying ones or stored collections.
  • Plain functions and constructors like Some can be used wherever a closure is expected.
  • Async closures (async |x|, Rust 1.85) return futures and use the AsyncFn* traits.

Next: Sorting, Searching and Comparison