Google News
logo
Rust - Interview Questions
What is a closure in Rust?
In Rust, a closure is an anonymous function that can capture variables from its surrounding environment and is capable of storing its captured state. Closures are similar to functions but have some additional capabilities due to their ability to access and manipulate captured variables.

Closures in Rust are defined using the `|parameter1, parameter2|` syntax, which specifies the parameters the closure accepts. The body of the closure follows the parameter list and contains the code that defines its behavior.

Here's a basic syntax example of a closure that adds two integers :
let add = |a: i32, b: i32| -> i32 {
    a + b
};​

In this example :
* The `|a: i32, b: i32|` part declares the parameters that the closure accepts.
* The `-> i32` part specifies the return type of the closure.
* The body of the closure, `a + b`, is the code that will be executed when the closure is called.

Closures can be stored in variables and used as values, just like any other data type. You can call a closure by using it as if it were a function, passing the required arguments.

Here's an example of calling the `add` closure :
let result = add(3, 5);
println!("Result: {}", result);​
This would output : `Result: 8`.

Closures are particularly useful in situations where you need to define short, one-time-use functions or when you want to capture variables from the surrounding context. The ability to capture variables allows closures to have access to the values of those variables even after they have gone out of scope.

In addition to capturing variables by value, closures in Rust can also capture variables by reference (`&`) or by mutable reference (`&mut`). This allows closures to modify the captured variables, as long as the captured variables are mutable and the closure itself is declared as mutable.

Closures provide a flexible and concise way to define functionality on the fly, making them a powerful tool in Rust for writing expressive and modular code.
Advertisement