Carry a little context.
Use anonymous functions and understand what they capture.
01 Understand the contract
A closure can capture surrounding values by shared borrow, mutable borrow, or ownership. Rust infers the least demanding capture that fits the body, while move transfers captured values into the closure. Fn, FnMut, and FnOnce describe how a closure can be called: a consuming closure may be callable only once, while a read-only one can often be called repeatedly. Capturing ownership does not by itself mean a closure must be FnOnce-only; what the body does with the captured data matters.
02 Make it concrete
This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.
fn main() {
let threshold = 10;
let large = |value: &i32| *value > threshold;
let values = [4, 12, 20];
let selected: Vec<_> = values.into_iter().filter(large).collect();
println!("{selected:?}");
}[12, 20]
- 1
The closure borrows threshold for its comparison.
- 2
filter asks the closure whether each item should remain.
- 3
collect materializes a new vector.
cargo run -p lesson_closures03 Mind the boundary
04 Your next build
Use a mutable closure to count calls, then verify the count after its last use.
Reveal one possible solution +
fn main() {
let mut calls = 0;
let mut tick = || {
calls += 1;
};
tick();
tick();
assert_eq!(calls, 2);
}05 Check your reasoning
What does move on a closure control?
Understand it.
Then make it yours.
Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.