At the end of the day, Rusdi wants the total of the big orders after a discount: keep the orders of $50 or more, take 10% off, then add them up. In this lesson the till counts in cents, so a $102 order is 10200. A for loop can do it, but it needs a temporary variable and an if inside. Rust has a shorter way. A closure is a small function without a name that can use the variables around it. An iterator is a way of taking the items of a collection (a group of values, like a Vec or an array) one at a time. Together they process data in one chain: filter, change, add up.
In the kitchen of Rusdi's Pancake Stall, that chain looks like this. Rusdi writes a small instruction card, "10% off for orders of $50 or more". Then a helper takes the slips off the spike one at a time. Each slip passes the sorting station, then the discount station, then reaches the cashier who adds them up. In code, the instruction card is a closure, the helper taking one slip at a time is an iterator, the stations are adapters (filter, map), and the cashier at the end is a consumer (sum). If there's no cashier, the helper never starts taking slips at all.
Closures: small functions without a name
This program makes two closures, discounted and add_delivery, then calls both:
fn main() {
let discount = 10;
let discounted = |price: u32| price - price * discount / 100;
let add_delivery = |total| total + 1000;
println!("{}", discounted(10200));
println!("{}", add_delivery(9180));
println!("Discount still {}%", discount);
}
9180
10180
Discount still 10%
- A closure's parameters go between two vertical bars,
|price: u32|, followed by the closure's body (its code, like a function body). A body of one expression needs no curly braces. A body of several lines is written|p| { ... }. - You may leave out a parameter's type, as in
|total|. The compiler guesses the type from the first use. discountedusesdiscount, a variable thatmainowns. Using a variable from outside the closure is called a capture. A plain function (fn) can't capture. If you write anfn discountedinsidemainthat usesdiscount, the compiler refuses it with E0434can't capture dynamic environment in a fn item.- A closure can be stored in a variable and called like a function:
discounted(10200)gives 9180.
Three ways to capture: Fn, FnMut, FnOnce
The compiler looks at what the closure's body does with the variables it captured, then gives it one of these traits:
| Trait | What the body does with the outside variable | May be called | Example |
|---|---|---|---|
Fn |
only reads it (borrows &) |
many times | |p| p - p * discount / 100 |
FnMut |
changes it (borrows &mut) |
many times, the closure is let mut |
|p| sales += p |
FnOnce |
gives what it owns away (a move) | once | || slip |
The code below makes one FnMut closure, record, and one FnOnce closure, hand_over:
fn main() {
let mut sales: u32 = 0;
let mut record = |price: u32| sales += price;
record(10200);
record(7000);
println!("Sales: {}", sales);
let slip = String::from("2x sweet pancake");
let hand_over = || slip;
let kitchen = hand_over();
println!("Kitchen: {}", kitchen);
}
Sales: 17200
Kitchen: 2x sweet pancake
recordchangessales, sorecordisFnMutand must be writtenlet mut record. Withoutmut, the compiler refuses with E0596cannot borrow `record` as mutable. As long asrecordwill still be called,recordholds the borrow&mut sales. So if you printsalesbetween tworecord(...)calls, the compiler refuses with E0502, the "many readers, or one writer" rule from the borrowing lesson.|| slipis a closure with no parameters (its two vertical bars are empty).hand_overreturnsslipitself, not a copy, sohand_overisFnOnce: after one call,sliphas already moved tokitchen. Calling it a second time is refused:closure cannot be invoked more than once because it moves the variable `slip` out of its environment.
The move keyword in front of a closure sets how it captures: the closure becomes the owner of the variables it captures, instead of borrowing them. But the trait is still decided by the closure's body. In this code, show captures text with move, then is called twice:
let text = String::from("2x sweet pancake");
let show = move || println!("{}", text);
show();
show();
This code prints 2x sweet pancake twice. The closure show now owns text, but its body only reads text, so show is still Fn and may be called many times. What can't be used any more is the variable text in main. If you use text after the let show line, the compiler refuses with E0382 borrow of moved value: `text` and marks value moved into closure here.
move and threads, briefly
A thread is a line of work that runs at the same time as other lines of work, like the kitchen cooking while the cashier serves. thread::spawn runs a closure on a new thread:
use std::thread;
fn main() {
let slip = String::from("2x sweet pancake");
let kitchen = thread::spawn(move || {
println!("Kitchen cooking: {}", slip);
});
kitchen.join().unwrap();
}
It prints Kitchen cooking: 2x sweet pancake. Without move, the compiler refuses with E0373 closure may outlive the current function, but it borrows `slip`, which is owned by the current function. This means the thread could keep running after main ends and slip is dropped, so a borrow of slip isn't enough. move hands slip to that thread. join() waits for the thread to finish. Threads come back in the smart pointers lesson.
iter, iter_mut and into_iter
These three methods each make an iterator from a Vec. The difference is how that iterator hands out each item of the Vec:
fn main() {
let mut orders = vec![10200, 7000, 3800];
for p in orders.iter() {
println!("read {}", p);
}
for p in orders.iter_mut() {
*p += 200;
}
println!("{:?}", orders);
for p in orders.into_iter() {
println!("take {}", p);
}
}
read 10200
read 7000
read 3800
[10400, 7200, 4000]
take 10400
take 7200
take 4000
iter()borrows each item to read it (&u32). The Vec can still be used afterwards.for p in orders.iter()is the same asfor p in &orders.iter_mut()borrows each item to change it (&mut u32), so*p += 200adds a $2 packaging fee (200 cents) to every order.for p in orders.iter_mut()is the same asfor p in &mut orders.into_iter()takes the Vec and hands out each item as a value you own (u32). After thatordersis not valid:orders.len()is refused with E0382, because`into_iter` takes ownership of the receiver `self`.for p in orders.into_iter()is the same asfor p in orders.
Adapters and consumers
An adapter turns one iterator into another iterator: map (changes each item), filter (keeps only the items that meet a condition), enumerate (numbers them), and zip (pairs them with another iterator). A consumer pulls the items of an iterator until there are none left, then gives a result: sum, count (counts the items), fold, collect, or for. This program uses all four adapters and several consumers:
fn main() {
let orders: Vec<u32> = vec![10200, 7000, 3800];
let customers = ["Sari", "Budi", "Rina"];
let dollars: Vec<u32> = orders.iter().map(|p| p / 100).collect();
let big = orders.iter().filter(|&&p| p >= 5000).count();
let total: u32 = orders.iter().sum();
let total_fold = orders.iter().fold(0, |acc, p| acc + p);
println!("{:?}", dollars);
println!("{} big orders", big);
println!("{} {}", total, total_fold);
for (i, p) in orders.iter().enumerate() {
println!("{}. {}", i + 1, p);
}
for (name, p) in customers.iter().zip(orders.iter()) {
println!("{}: {}", name, p);
}
}
[102, 70, 38]
2 big orders
21000 21000
1. 10200
2. 7000
3. 3800
Sari: 10200
Budi: 7000
Rina: 3800
collect()gathers the iterator's results into a new collection, here a Vec. Its type must be written:let dollars: Vec<u32>. Without a type, the compiler refuses with E0283type annotations needed.filterhands its closure a borrow of each item. The items fromiter()are already borrows (&u32), so the closure infiltergets a borrow of a borrow:&&u32. The pattern|&&p|opens both&, sopholds a plain number andp >= 5000works directly.|p| p >= 5000is refused:expected `&&u32`, found integer. Another way:|p| **p >= 5000(two*open two borrows). In the exercise,|x| *x % 2 == 0needs only one*, since%also works on a borrowed number (&i32).fold(0, |acc, p| acc + p)usesaccas the running result.accstarts at 0, and for each itemp, the result ofacc + pbecomes the newacc.sumis really afoldmade only for adding.enumerategives (number, item) pairs, with numbers starting at 0. That's why the code printsi + 1.zippairs item 0 ofcustomerswith item 0 oforders, item 1 with item 1, and so on.zipstops when the shorter iterator has no items left.
Lazy: nothing runs without a consumer
This program sets up a map that prints check for each order, then prints done. There is no consumer at the end. Before you look at the result, guess: what gets printed?
fn main() {
let orders = vec![10200, 7000, 3800];
orders.iter().map(|p| {
println!("check {}", p);
p * 2
});
println!("done");
}
warning: unused `Map` that must be used
--> src/main.rs:3:5
|
3 | / orders.iter().map(|p| {
4 | | println!("check {}", p);
5 | | p * 2
6 | | });
| |______^
|
= note: iterators are lazy and do nothing unless consumed
This is only a warning, so the program still runs. But it prints only done, without a single check. Adapters are lazy: map only sets up a station in the chain, and the station works only when a consumer at the end pulls the items. The compiler even warns you about this: iterators are lazy and do nothing unless consumed. The next program puts the consumer sum at the end of the chain, and each station prints its name:
fn main() {
let orders = vec![10200, 7000, 3800];
let total: u32 = orders
.iter()
.filter(|&&p| {
println!("filter {}", p);
p >= 5000
})
.map(|p| {
println!("map {}", p);
p - p / 10
})
.sum();
println!("Total: {}", total);
}
filter 10200
map 10200
filter 7000
map 7000
filter 3800
Total: 15480
The items go through one at a time to the end of the chain: 10200 is filtered and then discounted, and only after that does 7000 come in. 3800 doesn't meet the filter condition, so map is never called for it. No temporary Vec is made in between. The total is 9180 + 6300 = 15480. A chain like this is as fast as a for loop you write yourself: writing the code as a chain adds no cost while the program runs.
Try the same steps for vec![1, 2, 3, 4] with .filter(|&&x| x % 2 == 0).map(|x| x * 10).sum(). Only 2 and 4 meet the filter condition (they are even). map turns them into 20 and 40, so the total is 60.
⚠️ Chains that do nothing, or get refused
- A chain with no consumer. Not an error, just an
unused ... that must be usedwarning, and nothing runs. End the chain withsum,collect,countorfor. collect()with no type. E0283type annotations needed. Writelet result: Vec<u32> = ....- The double borrow in
filter.|p| p >= 5000is refused withexpected `&&u32`, found integer. Use|&&p|or**p. - Using the Vec after
into_iter()orfor p in orders. E0382. Useiter()or&ordersif you still need the Vec. - A closure that changes something but isn't
let mut. E0596. AnFnMutclosure must be kept in amutvariable.
TL;DR: A closure, like |price: u32| price - price * discount / 100, is a small function with no name that can capture (use) the variables around it, here discount. The closure's body decides its trait: if it only reads, Fn; if it changes something, FnMut (the closure must be let mut); if it gives a variable it owns away, FnOnce (it can be called only once). move makes a closure the owner of the variables it captures, for example for thread::spawn (which runs a closure on a new thread), but a closure that only reads is still Fn. An iterator takes the items of a collection one at a time: iter() borrows each item (&T), iter_mut() borrows it to change it (&mut T), and into_iter() uses up the Vec and hands out each item (T). Adapters (map, filter, enumerate, zip) turn an iterator into another iterator and are lazy: nothing runs until a consumer (sum, count, fold, collect with a type, for) pulls the items through the adapters, one at a time.
⚡ Small functions without a name
Write:
let discount = 10;
let discounted = |price: u32| price - price * discount / 100;
println!("{}", discounted(10200)); // 9180
Meaning: discounted is a closure: a small function with no name, stored in a variable. Its parameters go between two vertical bars, |price: u32|. Unlike an fn, a closure may use the variables around it, here discount. Using a variable from outside the closure is called a capture.
⚡ The body decides the trait
Guess first: let show = move || println!("{}", text);. move makes the closure show the owner of text, a String, and the closure's body only prints text. Because it uses move, can this closure be called only once?
No. move only sets how it captures. Its body only reads text, so its trait is still Fn and show may be called many times.
Meaning: The compiler gives each closure one trait, based on what the closure's body does with the variables it captured. Only reading means Fn, changing means FnMut (the closure must be let mut), and giving that variable away means FnOnce (it can be called only once).
⚡ Adapters, then a consumer
Write:
let total: u32 = orders
.iter()
.filter(|&&p| p >= 5000)
.map(|p| p - p / 10)
.sum();
Meaning: orders is a Vec of order prices in cents, and iter() makes an iterator that takes its items one at a time. filter passes on only the orders of 5000 or more (|&&p| opens two layers of borrow, so p holds a plain number). map takes 10% off each of those orders. filter and map are adapters (they change an iterator) and are lazy: nothing runs until a consumer like sum, at the end, pulls the items one at a time.