Closures
What you'll learn:
- write a closure and explain how it differs from an
fnfunction; - tell when a closure needs
mutand what themovekeyword changes; - take the items of a collection one at a time with an iterator and
next; - build
map,filter,sum,collectchains and explain why they are lazy.

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.
fn main() {
let k = 3;
fn add(x: i32) -> i32 {
x + k // ✗
}
println!("{}", add(2));
}error[E0434]: can't capture dynamic environment in a fn itemThe 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:
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:
let k = 3;is an ordinary variable inmain.|x| x + kis a closure: the parameterxstands between the vertical bars, and the body follows them.let add = …stores the closure in the variableadd, like any other value.add(2)calls the closure the same way as a function:xbecomes2, and the closure takeskfrommain. The result is5.add(10)prints13: each call readskagain.
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.
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:
- The first
priceholds100. - The closure
totalcaptures exactly this variable. let price = 250;creates a new variable with the same name. It does not change the first one; it only hides the namepricefrom the code below.total(2)computes2 * 100: the closure holds the firstprice, so the result is200.println!reads the nameprice, and that name now stands for the new variable: it prints250.
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:
fn main() {
let same = |x| x;
println!("{}", same(5));
println!("{}", same('a')); // ✗
}error[E0308]: mismatched typesThe 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 + kis a nameless function that sees the variables around it; a nestedfndoes not see them (E0434). - You call a closure like a function:
add(2). - A closure holds the variable it captured; a new
letwith 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.