DEV Community

Cover image for Understanding Rust Closures

Understanding Rust Closures

niran_jana profile image Niranjana ・2 min read

Closures are very interesting programming concepts. It helps save a lot of expensive calculations while writing programs.
Closure syntax of Rust is very similar to that of Ruby and SmallTalk.

Rust’s closures are anonymous functions you can save in a variable or pass as arguments to other functions. You can create the closure in one place and then call the closure to evaluate it in a different context. Unlike functions, closures can capture values from the scope in which they’re defined.

Closures are usually short and relevant only within a narrow context rather than in any arbitrary scenario. Within these limited contexts, the compiler is reliably able to infer the types of the parameters and the return type, similar to how it’s able to infer the types of most variables.

Closures don’t require you to annotate the types of the parameters or the return value like fn functions do. Type annotations are required on functions because they’re part of an explicit interface exposed to your users. Defining this interface rigidly is important for ensuring that everyone agrees on what types of values a function uses and returns. But closures aren’t used in an exposed interface like this: they’re stored in variables and used without naming them and exposing them to users of our library.

Let us dive into when to use closures. As mentioned in the definition, they are used at places when you need to call functions several times or repeat a value from a function call.

Consider the following snippet. This piece helps to explain how closures work and most importantly how and where to apply closures.

``` rust
 fn main() {
    let fact = |x| -> usize { (2..=x).product() };
    let five_fact = fact(5);
    println!("{}", five_fact);
    println!("{}", fact(8));



One of the first functions we write in any programming language is that of a factorial calculator. The code above is pretty much self-explanatory. Instead of defining the function, we have used anonymous functions, i.e, closures.

Discussion (0)

Editor guide