Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Learn RustChapter 6: Collections

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.

A closure in a let, called like a function
fn main() {
let double = |n: u32| n * 2;
println!("{}", double(21));
}
$ cargo run
42

Reaching 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.

PredictUsing a name from outside
fn main() {
let bonus = 3;
let add_bonus = |n: u32| n + bonus;
println!("{}", add_bonus(4));
}

What does this program print?

  • 4
  • 7
  • 3
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:

A fn cannot see the names of the function around it
fn main() {
let bonus = 3;
fn add_bonus(n: u32) -> u32 {
n + bonus
}
println!("{}", add_bonus(4));
}
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:

Borrow TimelineHow long does each borrow live?

Each bar is one borrow, drawn from its first use to its last. Scrub the line to see what is alive.

fn main() {
let mut seen = 0;
let mut note = |text: &str| {
seen += 1;
println!("{seen}: {text}");
};
note("hi");
println!("so far: {seen}");
note("there");
}
  • seen: owner — owner, lines 2–10
  • seen: note captures &mut seen — mutable borrow, lines 3–9
  • seen: 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.

PredictNote, note, then look
fn main() {
let mut seen = 0;
let mut note = |text: &str| {
seen += 1;
println!("{seen}: {text}");
};
note("hi");
note("there");
println!("so far: {seen}");
}

With the peek moved to the end, what is the LAST line it prints?

  • so far: 0
  • so far: 2
  • it 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. contains asks whether one piece of text appears anywhere inside another; &word lends it the word to look for.
  • word is not one of the closure's inputs. It came out of Command::Find(Some(word)), and the closure captures it, by borrow, because it only reads it. That is why word is 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 its to_line() and add one to found, a running total. If found is 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:

No type on m, and a field read before anything says what m is
struct Message {
author: String,
text: String,
}
 
fn main() {
let word = String::from("rust");
let history = vec![Message { author: String::from("you"), text: String::from("I like rust") }];
let is_match = |m| m.author == "you" && m.text.contains(&word);
for m in &history {
if is_match(m) {
println!("{}", m.text);
}
}
}
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".

Chatterbox v0.6 after lesson 6.4: the whole program (green lines are new in this lesson)
src/main.rs18 new lines
// Chatterbox: a small chat program, built one lesson at a time.
use std::collections::HashMap;
use std::io;
 
/// What the bot is called. A constant: fixed for the whole program.
const BOT: &str = "Chatterbox";
/// The version as a pair of numbers: (major, minor).
const VERSION: (u32, u32) = (0, 6);
/// The longest message we accept, in bytes.
const MAX_LEN: usize = 200;
/// What /help prints.
const HELP: &str = "commands: /help, /again, /history, /count, /remember <name> <fact>, /recall <name>, /find <word>, /say <text>, /shout <text>, /debug <text>, /quit (or /h, /q, /exit)";
 
/// One line of the conversation: who said it, and what they said.
struct Message {
author: String,
text: String,
}
 
impl Message {
/// Make a Message from two pieces of borrowed text.
fn new(author: &str, text: &str) -> Message {
Message {
author: String::from(author),
text: String::from(text),
}
}
 
/// The message as one transcript line: "you: hello".
fn to_line(&self) -> String {
format!("{}: {}", self.author, self.text)
}
 
/// The text in capitals, for /shout.
fn shout(&self) -> String {
self.text.to_uppercase()
}
}
 
/// Everything a line of input can mean. One enum, so a `match` on it must
/// handle every kind of line: the compiler checks that nothing is forgotten.
#[derive(Debug)]
enum Command {
Empty,
Help,
Quit,
Again,
History,
Count,
Remember(String, String),
Recall(Option<String>),
Usage(String),
Find(Option<String>),
Say(Option<String>),
Shout(Option<String>),
Unknown(String),
Debug(Option<String>),
Chat(String),
}
 
/// A borrowed Option<&str> turned into an owned Option<String>, so the
/// Command can keep the text after `line` is gone.
fn owned(text: Option<&str>) -> Option<String> {
match text {
Some(t) => Some(String::from(t)),
None => None,
}
}
 
/// Turn one line of input into a Command.
fn parse(line: &str) -> Command {
match first_word(line) {
"" => Command::Empty,
"/help" | "/h" => Command::Help,
"/quit" | "/q" | "/exit" => Command::Quit,
"/again" => Command::Again,
"/history" => Command::History,
"/count" => Command::Count,
"/remember" => match arg(line) {
Some(rest) => match arg(rest) {
Some(fact) => Command::Remember(String::from(first_word(rest)), String::from(fact)),
None => Command::Usage(String::from("/remember <name> <fact>")),
},
None => Command::Usage(String::from("/remember <name> <fact>")),
},
"/recall" => Command::Recall(owned(arg(line))),
"/find" => Command::Find(owned(arg(line))),
"/debug" => Command::Debug(owned(arg(line))),
"/say" => Command::Say(owned(arg(line))),
"/shout" => Command::Shout(owned(arg(line))),
word => {
if is_command(word) {
Command::Unknown(String::from(word))
} else {
Command::Chat(String::from(line))
}
}
}
}
 
/// The first line Chatterbox prints.
fn banner() -> String {
format!("{} v{}.{}", BOT, VERSION.0, VERSION.1)
}
 
/// The greeting, with a name filled in.
fn greeting(name: &str) -> String {
let mut text = format!("Hi {}! I'm {}.", name, BOT);
text.push_str(" Ask me anything.");
text
}
 
/// True when the text is a command: it starts with a slash.
fn is_command(text: &str) -> bool {
text.starts_with('/')
}
 
/// The first word of the text: a slice (&str) pointing into it, not a copy.
fn first_word(text: &str) -> &str {
match text.find(' ') {
Some(i) => &text[..i],
None => text,
}
}
 
/// The text after the command word, if there is any: Some("hello") for
/// "/say hello", None for a bare "/say". No more "" standing in for nothing.
fn arg(line: &str) -> Option<&str> {
match line.find(' ') {
Some(i) => {
let rest = line[i + 1..].trim();
if rest.is_empty() { None } else { Some(rest) }
}
None => None,
}
}
 
/// What the bot says back to an ordinary message (not a command).
fn reply(message: &str) -> String {
if message.len() > MAX_LEN {
format!("that is too long (the limit is {} bytes)", MAX_LEN)
} else if message.ends_with('?') {
String::from("Good question! I can only echo for now. Ask me again in chapter 9.")
} else {
format!("you said: {}", message)
}
}
 
fn main() {
let mut messages_seen: u32 = 0;
let quiet = false;
let mut last: Option<String> = None; // the last thing you said, for /again
let mut history: Vec<Message> = Vec::new(); // everything said so far, in order
let mut facts: HashMap<String, String> = HashMap::new(); // name -> fact, for /recall
 
println!("{}", banner());
println!("What should I call you?");
let mut name_line = String::new();
io::stdin().read_line(&mut name_line).unwrap();
let name = name_line.trim();
if !quiet {
println!("{}", greeting(name));
}
 
let mut line = String::new();
loop {
line.clear();
let bytes = io::stdin().read_line(&mut line).unwrap();
if bytes == 0 {
break; // no more input: the keyboard was closed
}
let message = line.trim();
match parse(message) {
Command::Empty => {} // nothing typed: nothing to answer
Command::Quit => {
println!("bot: bye, {}!", name);
break;
}
Command::Help => println!("bot: {}", HELP),
Command::Again => {
if let Some(text) = &last {
println!("bot: {}", reply(text));
} else {
println!("bot: nothing to repeat yet");
}
}
Command::History => {
if history.is_empty() {
println!("bot: nothing said yet");
} else {
for (i, m) in history.iter().enumerate() {
println!("{}. {}", i + 1, m.to_line());
}
}
}
Command::Count => {
let mut bytes = 0;
for m in &history {
bytes += m.text.len();
}
println!("bot: {} messages, {} bytes of text", history.len(), bytes);
}
Command::Remember(key, fact) => {
println!("bot: got it: {} is {}", key, fact);
facts.insert(key, fact);
}
Command::Recall(Some(key)) => match facts.get(&key) {
Some(fact) => println!("bot: {} is {}", key, fact),
None => println!("bot: I don't know anything about {}", key),
},
Command::Recall(None) => {
if facts.is_empty() {
println!("bot: I don't remember anything yet. Try /remember");
} else {
// A HashMap has no order, so sort the names before printing them.
let mut names = Vec::new();
for name in facts.keys() {
names.push(name.as_str());
}
names.sort();
println!("bot: I remember: {}", names.join(", "));
}
}
Command::Find(Some(word)) => {
// A closure: a small function made on the spot. It borrows `word`.
let is_match = |m: &Message| m.author == "you" && m.text.contains(&word);
let mut found = 0;
for m in &history {
if is_match(m) {
println!("{}", m.to_line());
found += 1;
}
}
if found == 0 {
println!("bot: you never said {}", word);
}
}
Command::Find(None) => println!("bot: find what? Try /find hello"),
Command::Usage(form) => println!("bot: try {}", form),
Command::Say(Some(text)) => println!("bot: {}", text),
Command::Say(None) => println!("bot: say what? Try /say hello"),
Command::Shout(Some(text)) => println!("bot: {}", Message::new("you", &text).shout()),
Command::Shout(None) => println!("bot: shout what? Try /shout hello"),
Command::Unknown(word) => {
println!("bot: I don't know the command {}. Try /help.", word)
}
Command::Debug(Some(text)) => println!("bot: {:?}", parse(&text)),
Command::Debug(None) => println!("bot: debug what? Try /debug /say hi"),
Command::Chat(text) => {
messages_seen += 1;
let said = Message::new("you", &text);
let answer = Message::new("bot", &reply(&said.text));
println!("bot: {}", answer.text);
history.push(said);
history.push(answer);
// Message::new made the history its own copy, so `text` itself can
// be handed to `last` for /again: no extra copy needed.
last = Some(text);
}
}
}
println!("messages so far: {}", messages_seen);
}
You type
Sam
I like rust
pizza is good
rust is fun
/find rust
/find tea
/find
/quit
Chatterbox prints (a real run)
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.

Try itPractice: the long ones

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.

struct Message {
author: String,
text: String,
}
 
impl Message {
fn new(author: &str, text: &str) -> Message {
Message { author: author.to_string(), text: text.to_string() }
}
}
 
fn long_messages(history: &[Message], limit: usize) -> Vec<String> {
// keep the texts longer than limit, shortest first
Vec::new()
}
 
fn main() {
let history = vec![Message::new("sam", "hi"), Message::new("ada", "this one is quite long")];
println!("{:?}", long_messages(&history, 5));
}

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.

Self-check

Say it out loud, then reveal

Self-checkRetrieval beats re-reading
What does <code>|n| n + 1</code> mean?Reveal
A closure: given n, produce n plus one. The inputs sit between the bars and the result follows.
What does it mean for a closure to capture a name, and how does it hold it?Reveal
It uses a name from the surrounding code without it being passed in. It holds it as a borrow: shared if it only reads, exclusive if it changes it.
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
A fn only sees its inputs and things defined for the whole program, such as constants (E0434). A closure carries a borrow of what it uses from around it.

That is lesson 6.4. Tick it off so the course remembers where you are.

Next: 6.5 Iterators →

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.

Learn Rust by building a chat app · Lesson 6.4 · every compiler message above is real output from rustc 1.99.0 (b940084d7 2026-09-28) (edition 2024) · Vibe Engines · 2026