Terminology (5)Terms used in this lesson
Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.
- Fn
- Callable through shared access to its environment (&self). Interior mutability such as Cell can still change reached data; Fn is not a side-effect-free guarantee.
- FnMut
- Callable through mutable access to its environment (&mut self). Fn callbacks support it too. The owned bindings and parameters called this way here need mut to obtain that access.
- FnOnce
- Callable by taking ownership of its receiver (self). Every closure supports FnOnce; a bound of only FnOnce gives an API one consuming call, without promising reuse.
- move closure
- A closure capturing needed values by value. Copy values are copied; a String or &mut reference is moved. Moving a reference does not move its referent.
- Callback bound
- A constraint such as F: FnMut(&str) describing how an API may call the supplied callable value and which implementations it accepts.
Capture ownership and callable access
A Rust closure has an environment containing the values it captures. How that environment is obtained and how its body uses it are separate questions: move selects capture by value, while the body determines which call traits the closure implements.
Fn supports calls through shared access, FnMut through mutable access, and FnOnce through ownership of the receiver. These describe calling capabilities rather than purity. Match the API’s required access and reuse to the callback’s work, then check which captured data remains with the caller after invocation.
01Read or change
Which access does the arrival counter need?
A registration batch uses callbacks to welcome visitors, reconcile admission payments and build badge lines. The runner must accept the welcome counter, the caller must see the payment accumulator, and repeated badge calls must keep their header available. Which captures and receiver bounds let those callbacks do their work?
Start with two reduced callbacks for registration: show prints the closing time, while enter advances the caller’s ordinary visitor count. The sequence calls show, enter twice, then show. Predict the final visitor observation and the binding that needs mutable access.
show is bound with let; enter is bound with let mut.
fn main() {
let closing = 18;
let mut visitors = 0;
let show = || println!("open until {closing}");
let mut enter = || visitors += 1;
show();
enter();
enter();
show();
println!("{visitors} visitors");
}
cargo run
Use the Rust setup from the first reading and replace src/main.rs for each experiment.
02Give away
Can the notice callback give its owned text away twice?
A batch may also keep text for later output. Before reusing such a callback for visitor badges, inspect hand_over: its result is the captured owned String itself. The source attempts two calls; predict whether that ownership contract permits them.
The closure body is just notice, so calling it returns the String.
fn main() {
let notice = String::from("closing in 10 minutes");
let hand_over = || notice;
let first = hand_over();
let second = hand_over();
println!("{first} / {second}");
}
03Callback bounds
Which callback contract lets the runner reuse its action?
The runner now determines how a callback can be invoked. This reduced repeat API receives one action and calls it several times, first for stamps and then for a caller-owned log. Predict whether the API accepts those callbacks and what the caller reads afterwards.
repeat is generic over F: FnMut() and declares mut action.
fn repeat<F: FnMut()>(times: u32, mut action: F) {
for _ in 0..times {
action();
}
}
fn main() {
let mut stamps = 0;
repeat(3, || stamps += 1);
println!("{stamps} stamps");
let mut log = Vec::new();
repeat(2, || log.push("tick"));
println!("{log:?}");
}
04Repair the registration callbacks
Welcome and count, reconcile admissions, then print every badge
The registration batch first welcomes every supplied visitor and reports the batch count. Its payment pass prints a running admission total after every amount, then reconciles that total with the caller’s final report. Its badge pass reuses one callback for every name; badge text must remain available for the next call instead of being consumed by the first visitor.
Each pass has a supplied reader and complete caller. The input batch is bounded and stays in memory. The callback contracts decide whether repeated calls may read, mutate or consume captured data; they do not promise that every closure needs the same trait.
Repair the registration callbacks
Accept the welcome callback, reconcile caller-visible admission totals, then fill the caller-owned badge report with a reusable callback.
Sources
Sign in to keep your read marks on every device. Sign in
Was this helpful?