Practical Rust
Closures
Capturing the Environment
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
fn main() {
let factor = 3;
let scale = |n: i32| n * factor;
let result = scale(5);
println!("{result}");
}
closure
`|n| ...` is an anonymous function value.
capture
The closure captures `factor` from its scope.
call
`scale(5)` runs the closure with an argument.