Skip to content
Theory · Closures and iterators · lesson 1 of 7

Closures

What you'll learn

What you'll learn:

  • write a closure and explain how it differs from an fn function;
  • tell when a closure needs mut and what the move keyword changes;
  • take the items of a collection one at a time with an iterator and next;
  • build map, filter, sum, collect chains and explain why they are lazy.
An empty backpack fn and a packed backpack |x| with a map k inside, and behind them a faint wardrobe, fridge and shelf

Picture packing a backpack for a hike. The wardrobe, the fridge and the bookshelf stay at home. Into the backpack go the things you need on the way: water, a map, a flashlight. On the trail you take things from the backpack instead of running home for them.

An fn function sets off with an empty backpack. It sees only its own parameters and its own variables. Let's check: we declare a function right inside main and ask it to read the variable k from main.

Rust
fn main() {
    let k = 3;

    fn add(x: i32) -> i32 {
        x + k // ✗
    }

    println!("{}", add(2));
}
TEXT
error[E0434]: can't capture dynamic environment in a fn item

The program does not compile. A nested fn is a function like any other: it does not see the variables of the code around it, even when it is written inside main. The compiler itself suggests the way out: use a closure.

A closure

A closure is a nameless function written right inside an expression that sees the variables around it. Let's rewrite the example:

Rust
fn main() {
    let k = 3;
    let add = |x| x + k;
    println!("{}", add(2)); // 5
    println!("{}", add(10)); // 13
}

Let's walk through the example line by line:

  1. let k = 3; is an ordinary variable in main.
  2. |x| x + k is a closure: the parameter x stands between the vertical bars, and the body follows them.
  3. let add = … stores the closure in the variable add, like any other value.
  4. add(2) calls the closure the same way as a function: x becomes 2, and the closure takes k from main. The result is 5.
  5. add(10) prints 13: each call reads k again.

Using a variable from the surroundings in a closure's body is called capture. The captured values are what the backpack holds.

How does a closure differ from a function? Interviewers like to ask this. The short answer: a closure has no name, it is written right inside an expression, and it captures the variables around it, while an fn function does not see them.

Ways to write it

A closure has three forms, and they differ in how much you write yourself.

The short form

|x| x + k has parameters without types and a body of one expression. The compiler infers the parameter and result types itself, from the body and from the calls. This is the most common form.

The full form

|x: i32| -> i32 { x * 2 } has types, like a function. When the result type is given after ->, the body must be written in curly braces. If you store such a closure in double, then double(4) returns 8.

No parameters

|| println!("hello") uses two bars in a row to say there are no parameters. You call such a closure with empty parentheses: after let hello = || println!("hello"); the call hello() prints hello.

The backpack holds that very variable

Here the backpack picture needs a correction. A closure remembers not the name but the very variable that had this name when the closure was created. Remember shadowing from the theme on variables? A new let with the same name puts a new box in front of the old one, and the old one does not go anywhere.

Rust
fn main() {
    let price = 100;
    let total = |count| count * price;
    let price = 250;
    println!("{} {}", total(2), price); // 200 250
}

Let's go step by step:

  1. The first price holds 100.
  2. The closure total captures exactly this variable.
  3. let price = 250; creates a new variable with the same name. It does not change the first one; it only hides the name price from the code below.
  4. total(2) computes 2 * 100: the closure holds the first price, so the result is 200.
  5. println! reads the name price, and that name now stands for the new variable: it prints 250.

In Python the name is looked up at the moment of the call. Rust picks the variable at the moment the closure is created, and that does not change later.

Common mistake

One closure was called with arguments of different types, as if it were generic:

Rust
fn main() {
    let same = |x| x;
    println!("{}", same(5));
    println!("{}", same('a')); // ✗
}
TEXT
error[E0308]: mismatched types

The program does not compile. The compiler infers the parameter type from the first call: same(5) made x an integer. A closure has one set of types, and the second call with a char no longer fits it. When you need a function for many types, you write a generic fn with a parameter T.

Key points

  • The closure |x| x + k is a nameless function that sees the variables around it; a nested fn does not see them (E0434).
  • You call a closure like a function: add(2).
  • A closure holds the variable it captured; a new let with the same name creates a different variable.
  • A closure's parameter types are fixed by the first call, so a call with another type is error E0308.