Closures in Rust
Anonymous functions that capture their environment.
fn main() {
let factor = 3;
let scale = |x: i32| x * factor;
let mut counter = 0;
let mut bump = || {
counter += 1;
counter
};
bump();
let scaled = scale(10);
println!("{scaled} {}", bump());
}
How it works
scalecapturesfactorby reference.- A
mutclosure captures and mutatescounter. - Closures are called like ordinary functions.
Keywords and builtins used here
fni32letmainmut
The run, in numbers
- Lines
- 14
- Characters to type
- 195
- Tokens
- 67
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 40 seconds.
Step 1 of 3 in Closures & folding, step 6 of 14 in Iterators & closures.