WeCodeAcademy

Rust Closures

A closure is an anonymous function that can capture variables from its surroundings: |x| x + 1.

ExampleRust
fn apply<F: Fn(i32) -> i32>(f: F, x: i32) -> i32 {
    f(x)
}

fn make_adder(n: i32) -> impl Fn(i32) -> i32 {
    move |x| x + n
}

fn main() {
    let double = |x| x * 2;
    println!("{}", double(21));

    let factor = 3;
    let times = |x| x * factor; // captures factor
    println!("{}", apply(times, 5));

    let add5 = make_adder(5);
    println!("{}", add5(10));

    let mut counter = 0;
    let mut inc = || {
        counter += 1;
        counter
    };
    inc();
    inc();
    println!("{}", counter);
}
Output
42
15
15
2
Quick check

What does move do in front of a closure?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.