til/
← back to the board

2026-07-29 · 1 min read

Rust closures

rust

A closure is an inline, unnamed function (|params| body) that can, unlike a regular fn, capture variables from the scope it was written in — not just its own parameters.

let factor = 5;
let scale = |x| x * factor;  // captures `factor` — a plain `fn` couldn't do this

Why they matter — the "hand over a closure" pattern

Some functions generate a value internally that the caller has no way to access directly. The only way the caller can use that value is to hand the function a closure; the function calls it, supplying the value as an argument.

fn cook(&self, callback: impl Fn(i32)) {
    let dish = 7;       // caller could never have this directly
    callback(dish);     // hands it to whatever closure was passed in
}
 
kitchen.cook(|x| serve(x, &chef));
//            ^-- gets `dish` from cook        ^-- captured from outer scope