typestar

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

  1. scale captures factor by reference.
  2. A mut closure captures and mutates counter.
  3. Closures are called like ordinary functions.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 3 in Closures & folding, step 6 of 14 in Iterators & closures.

← Previous Next →

Closures in other languages