16 / 35

Rust for the Web· 9 min read· Lesson 16 of 35

Closures and Iterators

Part 1 · Rust. Use closures and iterator chains (map, filter, collect, sum) to turn lists of café orders into totals and menus, the way web code does.

Imagine the Rusty Bean Café manager asks, “What is the total of all today’s orders over five dollars?” You could write a loop with a counter and an if. Rust offers a tidier way: describe what you want as a short chain of steps. The two tools that make this possible are closures and iterators.

Closures: small unnamed functions

A closure is a function without a name that you can store in a variable or hand to another function. It is written with vertical bars around the inputs:

src/main.rs
fn main() {
let add_tax = |price_cents: u32| price_cents + price_cents / 10;
println!("{}", add_tax(350));
}
Output
385
  1. |price_cents: u32| lists the input, like a function’s parentheses.
  2. What follows is the body. For one expression, no braces are needed.
  3. add_tax(350) calls it like any function. Ten percent of 350 is 35, so we get 385.

Rust can usually guess the types, so you will often see |p| p + p / 10 once the compiler can infer p from how the closure is used.

Closures can remember their surroundings

Here is what makes closures special: they can use variables from the place where they were written.

fn main() {
let discount_cents = 50;
let apply_discount = |price: u32| price - discount_cents;
println!("{}", apply_discount(350));
}
Output
300

discount_cents is not an input, yet the closure uses it. We say the closure captures it. A normal fn cannot do this.

Note

By default a closure borrows what it captures, following the same rules you learned in the borrowing lesson. If a closure must take ownership (for example, to run later on another thread), write move |x| .... You will meet move again in the async lesson.

Iterators: a conveyor belt of items

An iterator hands you the items of a collection one at a time, like a conveyor belt at a sushi bar. You get one by calling .iter() on a Vec.

let prices = vec![450, 325, 300];
for price in prices.iter() {
println!("{}", price);
}

The for loop uses an iterator behind the scenes anyway. The real power is that iterators have adapter methods you can chain.

map, filter, collect, sum

Let us model a few orders:

src/main.rs
struct Order {
id: u32,
total_cents: u32,
paid: bool,
}
fn main() {
let orders = vec![
Order { id: 1, total_cents: 450, paid: true },
Order { id: 2, total_cents: 825, paid: false },
Order { id: 3, total_cents: 1200, paid: true },
];
// 1. Only paid orders, adding up their totals
let revenue: u32 = orders
.iter()
.filter(|o| o.paid)
.map(|o| o.total_cents)
.sum();
// 2. The ids of orders over five dollars
let big_ids: Vec<u32> = orders
.iter()
.filter(|o| o.total_cents > 500)
.map(|o| o.id)
.collect();
println!("Revenue: {} cents", revenue);
println!("Big orders: {:?}", big_ids);
}
Output
Revenue: 1650 cents
Big orders: [2, 3]

Walk through the first chain:

  1. .iter() starts the conveyor belt of &Order items.
  2. .filter(|o| o.paid) keeps only items where the closure returns true.
  3. .map(|o| o.total_cents) transforms each remaining order into just its total.
  4. .sum() adds everything up and ends the chain with a single number.

The second chain ends with .collect(), which gathers the items into a new collection. Because collect can build many kinds of collections, you tell it which one: Vec<u32> here.

Warning

Iterator adapters are lazy: .filter(...) and .map(...) do nothing until something at the end (sum, collect, a for loop) pulls items through. If you forget the final step, the compiler warns: unused ... that must be used. Add .collect() or .sum().

Tip

If collect() complains about “type annotations needed”, tell it what you want, either with a typed variable (let ids: Vec<u32> = ...) or the “turbofish” form: .collect::<Vec<u32>>().

Functions are values too

A function’s name, written without the (), is a value you can pass around, just like a closure. When you write format_price(450) you call the function; when you write format_price you hand over the function itself.

src/main.rs
fn format_price(cents: &u32) -> String {
format!("${}.{:02}", cents / 100, cents % 100)
}
fn main() {
let prices = vec![450, 325, 300];
let labels: Vec<String> = prices.iter().map(format_price).collect();
println!("{:?}", labels);
}
Output
["$4.50", "$3.25", "$3.00"]

.map(format_price) does the same as .map(|p| format_price(p)), only shorter. The function must accept what the iterator hands over; here that is &u32, so format_price takes &u32.

Note

This idea returns later. In Laravel Rust you register a route by passing a handler function by name, with no parentheses, in the same way you just passed format_price to map. The framework calls it when a visitor arrives.

More handy iterator methods

Method What it does Café example
count() How many items Number of orders
any(|x| ...) Is at least one item a match? Any unpaid order?
all(|x| ...) Do all items match? Everything paid?
find(|x| ...) First match, as an Option Order with id 2
max_by_key(|x| ...) Largest by a key Priciest order
let any_unpaid = orders.iter().any(|o| !o.paid);
let first_big = orders.iter().find(|o| o.total_cents > 1000);

any_unpaid is true. find returns an Option<&Order> (an Option you already know how to handle with match or if let), because there might be no match.

Changing items in place

.iter() borrows read-only. For changes use .iter_mut():

let mut prices = vec![450, 325, 300];
for p in prices.iter_mut() {
*p += 10;
}

The *p reaches through the reference to the number itself, as in the borrowing lesson. Prices become [460, 335, 310].

Why web code uses them

Web handlers constantly reshape data: take the rows from a database, keep the visible ones, turn each into a response item, collect them into a list. Chains of filter, map and collect say that in a few readable lines. Closures also appear whenever a framework asks “what should I do when this happens?”, such as a callback that runs for each item or a handler registered for a request. In Laravel Rust you will map a list of models into display rows in exactly this way.

Try it yourself

  1. Given let prices = vec![450, 325, 300, 200];, produce a new Vec<u32> where every price has a 10% discount (p - p / 10).
  2. Using the orders from this lesson, print how many orders are unpaid.
Show solution
fn main() {
let prices = vec![450, 325, 300, 200];
let discounted: Vec<u32> = prices.iter().map(|p| p - p / 10).collect();
println!("{:?}", discounted);
}
Output
[405, 293, 270, 180]

For the second one:

src/main.rs
struct Order {
id: u32,
total_cents: u32,
paid: bool,
}
fn main() {
let orders = vec![
Order { id: 1, total_cents: 450, paid: true },
Order { id: 2, total_cents: 825, paid: false },
Order { id: 3, total_cents: 1200, paid: true },
];
let unpaid = orders.iter().filter(|o| !o.paid).count();
println!("{} unpaid", unpaid);
}
Output
1 unpaid

(The id field is never read here, so the compiler may warn about it; that is harmless.) Note that p in the first solution is &u32; Rust lets p - p / 10 work on references to numbers.

Recap

  • A closure is an unnamed function written |input| body that can capture nearby variables.
  • An iterator produces items one at a time; get one with .iter().
  • filter keeps, map transforms, and sum/collect/count finish the chain.
  • Adapters are lazy until a final step pulls the items through.
  • Web code uses these chains constantly to reshape data.

What’s next

Our programs are growing, so it is time to organise them into files and use other people’s code. Continue to Modules and Crates.

0 of 35 lessons complete

Search lessons

Type to search all lessons.