Help understanding Closures

I'm struggling to fully understand closures. I understand that it is an anonymous function as it isn't fn declared with a name. I don't understand when to use them, when not, or the advantage versus regular functions besides speed. Any insight?

Closures are anonymous functions that can capture (or close over) values in their defining scope. For example,

fn foo() {
    let mut x = 1;
    let mut f = || x += 1;
    f();
    f();
    println!("{}", x);  // prints 3
}

Closures are often passed into functions like the Iterator methods -

nums.map(|x| x + 1)

passes a closure that increments a value to the map function.

In general, if you'd be defining a function just to pass as an argument to a single function, I'd use a closure. You could write the previous example as

fn incr(x: u32) -> u32 {
    x + 1
}
nums.map(incr)

but it's more compact to write a simple function like that as |x| x + 1 so you don't have to name it.

If you really want to get into the weeds, closures are just structs (whose members are the values they capture) which implement Fn for some argument and return values, which lets them be called as if they were functions.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.