Lesson 6.4 · 10 min
Small functions on the spot
Chatterbox wants a /find command: show every line you said that contains a word. The question "is this message a match?" needs the word you just typed, and an ordinary function cannot see it. A closure can.
Adds to Chatterbox/find, with a closure.
A function with no name
Every function so far had a name and lived on its own, at the left edge of the file. A closure is a small function you write in the middle of other code, right where you need it, without a name. The inputs go between two bars, then the result: |n| n * 2 means "given n, give back n times two". If you want to use it more than once, put it in a let like any other value and call it with brackets, exactly like a function.
$ cargo run
42Reaching outside
So far that is just a shorter way to write a function. Here is the part that makes closures worth a lesson: a closure can use the names that exist around it. Rust calls that capturing.
What does this program print?
473
Reveal the answer
The program prints: 7 The closure never declared bonus and nobody passed it in. It reached out to the one in main and used it. The closure only reads bonus, so it only borrows it: bonus is still yours afterwards.
A named function cannot do that. A fn is a separate piece of the program that can be called from anywhere, at any time, so it is only allowed to see what it is given through its inputs, plus things defined for the whole program, such as constants. Write the same thing as a fn inside main and the compiler says no:
error[E0434]: can't capture dynamic environment in a fn item --> src/main.rs:4:13 | 4 | n + bonus | ^^^^^ | = help: use the `|| { ... }` closure form instead
E0434, "can't capture dynamic environment in a fn item", is the compiler's way of saying exactly that, and its help line suggests the fix: use a closure instead. So what is a closure, underneath? It is a small hidden value that holds whatever it captured, here a borrow of bonus, glued to the code you wrote between the braces. Calling it runs that code with those borrows in hand.
Capturing is borrowing
Because a capture is a borrow, the borrowing rules of chapter 4 hold here without a single change. A closure that only reads a name takes a shared borrow. A closure that changes a name takes the exclusive one, so the closure itself must be let mut, and for as long as that closure is still going to be called, nobody else may even look at the name. Here a closure counts the messages it notes, and main tries to peek at the count in the middle:
Each bar is one borrow, drawn from its first use to its last. Scrub the line to see what is alive.
seen: owner — owner, lines 2–10seen: note captures &mut seen — mutable borrow, lines 3–9seen: println! reads seen — shared borrow, lines 8–8
The exclusive borrow starts when note is made on line 3 and lasts until its last call on line 9. Line 8 wants to read seen inside that stretch, which is E0502 from lesson 4.4, word for word. The fix is the one you already know: finish with the borrow, then look. Move the peek after the last call.
With the peek moved to the end, what is the LAST line it prints?
so far: 0so far: 2it does not compile
Reveal the answer
The program prints: so far: 2 It compiles: the closure's last call is on line 8, so its exclusive borrow is over before line 9 reads seen. The closure changed the real seen, not a copy of it, so both notes count and the program prints 1: hi, 2: there, then so far: 2.
Handing a closure to a method
A closure is a value, so you can pass it to a function. The standard library is full of methods that do some walking for you and ask for a closure to say what you want done with each item. One you can use today is sort_by_key, which sorts a Vec by whatever the closure returns for each item: names.sort_by_key(|n| n.len()) puts the shortest names first. The method does the comparing and the swapping; you only say what to compare. Items with equal keys keep the order they had.
Chatterbox v0.6: /find
Here is the whole program after this lesson, new lines in green. /find rust prints every line you said that contains rust. It has its own variant, Find(Option<String>), built in parse with arg and owned exactly like /recall, and the help text lists /find <word>. The work happens in the Find(Some(word)) arm:
let is_match = |m: &Message| m.author == "you" && m.text.contains(&word);makes the closure. Given a borrowed message, is it yours, and does its text contain the word?&&means "and": both halves must be true.containsasks whether one piece of text appears anywhere inside another;&wordlends it the word to look for.wordis not one of the closure's inputs. It came out ofCommand::Find(Some(word)), and the closure captures it, by borrow, because it only reads it. That is whywordis still there afterwards, to print "you never said tea" when nothing matched.- The author check matters. Every message is answered with
bot: you said: …, which repeats your words, so without it most hits would show up twice. - Then it is the walk from lesson 6.2:
for m in &history, and for each message,if is_match(m)print itsto_line()and add one tofound, a running total. Iffoundis still 0 at the end, say so.
Why does the closure spell out m: &Message? Here it has to. The first thing this closure does with m is read a field, m.author, and to know what .author means the compiler must already know what m is. Nothing has told it yet: the closure is made on its own line, before the loop that calls it. Leave the type out and the build stops:
error[E0282]: type annotations needed --> src/main.rs:9:21 | 9 | let is_match = |m| m.author == "you" && m.text.contains(&word); | ^ - type must be known at this point | help: consider giving this closure parameter an explicit type | 9 | let is_match = |m: /* Type */| m.author == "you" && m.text.contains(&word); | ++++++++++++
E0282, "type annotations needed", points at m and says the type "must be known at this point", right where the field is read. Other closures can leave their types out: names.sort_by_key(|n| n.len()) compiles, because sort_by_key already knows its items are Strings before the closure's body is read. A closure kept in a let has no such helper, so when it reads a field, give its input a type.
A bare /find is Find(None), which answers "find what? Try /find hello".
Sam I like rust pizza is good rust is fun /find rust /find tea /find /quit
Chatterbox v0.6 What should I call you? Hi Sam! I'm Chatterbox. Ask me anything. bot: you said: I like rust bot: you said: pizza is good bot: you said: rust is fun you: I like rust you: rust is fun bot: you never said tea bot: find what? Try /find hello bot: bye, Sam! messages so far: 3
Download this version (zip)Unzip, then cargo run inside the folder.
A practice exercise on a cut-down Message. Write long_messages: return the text of every message whose length in bytes (len()) is more than limit (strictly more), shortest first. Make a closure that answers "is this message long?" (it will need to capture limit), use it in a for loop, then sort what you kept with sort_by_key. The history comes in as &[Message], a borrowed view of the list, as in the last three lessons.
A practice exercise on a cut-down Message. Write long_messages: return the text of every message whose length in bytes (len()) is more than limit (strictly more), shortest first. Make a closure that answers "is this message long?" (it will need to capture limit), use it in a for loop, then sort what you kept with sort_by_key. The history comes in as &[Message], a borrowed view of the list, as in the last three lessons.
Hidden tests (4): exactly_the_limit_is_not_long empty_history drops_short_messages shortest_first
This exercise runs real Rust in your browser through the official Rust Playground, so it needs JavaScript.
What you have now
A closure is a function you write where you use it. It can reach the names around it, and it does so by borrowing them, under exactly the rules chapter 4 taught. You can keep one in a let and call it, or hand it to a method that does the walking. That second use is about to get much bigger: the next lesson strings several such methods together into one chain, and Chatterbox learns your favourite words.
Say it out loud, then reveal
What does <code>|n| n + 1</code> mean?Reveal
What does it mean for a closure to capture a name, and how does it hold it?Reveal
Why did <code>println!("so far: {seen}")</code> between two calls of <code>note</code> fail?Reveal
note held an exclusive borrow of seen from where it was made until its last call. Reading seen inside that stretch is E0502.Why can a closure use <code>bonus</code> when a <code>fn</code> written in the same place cannot?Reveal
That is lesson 6.4. Tick it off so the course remembers where you are.
Go deeper
Questions people ask
What is a closure in Rust?
A function without a name, written inline with |inputs| result, that can use names from the code around it by borrowing them.
What does error E0434 mean?
A fn written inside another function tried to use one of that function's local names. A fn can only see its own inputs and things defined for the whole program, such as constants. Use a closure instead, which can capture the name.
Is a closure the same as a Python lambda?
It is the nearest idea. A Rust closure can also have a full block body in braces, it is typed, and the compiler checks how it borrows what it captures.
Does sort_by_key keep equal items in order?
Yes. It is a stable sort, so items with equal keys stay in their original order.