A closure is an inline function that can capture surrounding variables, such as a scaling factor.

Program

Play the program to scale a number with a captured factor.

closures.rs
Replay: real traced execution (multi-file project)
fn main() {
    let factor = 3;
    let scale = |n: i32| n * factor;
    let result = scale(5);
    println!("{result}");
}
  1. factor ← 3, scale ← (empty), result ← 15

    1fn main() {2    let facto→ 3r = 3;3    let scal→ (empty)e = |n: i32| n * factor;4    let resul→ 15t = scale(5);5    println!("{result}");6}
    output15
closure `|n| ...` is an anonymous function value.
capture The closure captures `factor` from its scope.
call `scale(5)` runs the closure with an argument.