Rust Closures
Capture a small value while keeping the closure’s role clear.
How it works
A closure is an anonymous callable that can capture values from its environment. Capture and call behaviour depend on how those values are used, leading to Fn, FnMut or FnOnce traits. A move closure moves or copies captured values into its environment; it does not automatically create a thread. Use named functions when a reusable interface or clearer type boundary helps.
Run the code
Reviewed with Rust 1.97.0, edition 2024, using the standard library only. Save the complete download as lesson-name.rs in a separate learning folder, compile with rustc --edition=2024 lesson-name.rs and run the resulting program (lesson-name.exe on Windows). Use the actual lesson filename. The final project includes complete Cargo package files; run cargo test --offline and cargo run --offline from that separate package folder. There is no Rust browser runner; PHP, Apache and MySQL are not needed.
This complete example was executed in the stated local review environment.
Example
fn main() {
let multiplier = 3_u32;
let packets = |trays: u32| trays * multiplier;
assert_eq!(packets(4), 12);
assert_eq!(multiplier, 3);
println!("Closure converts four trays to {} packets", packets(4));
}
Expected result
Closure converts four trays to 12 packets
The closure reads a small Copy value from its surrounding scope. Both the calculation and the original binding remain usable. Larger captured values may introduce moves or borrows that affect later code, so review what the callable actually owns before storing it or sending it elsewhere.
Primary technical reference: Rust documentation.