What are Closures in Rust?
A closure in Rust is an anonymous function that can capture variables from its surrounding environment.
Just as regular functions, they can:
- take inputs
- process data
- return values
However, they are more flexible because they can access variables without explicitly passing them as arguments.
Closures in Rust are defined using pipes (|) to specify parameters and can be used inline, passed to functions or returned from them. In this case, we will see just the most basic example with inline syntax.
They also allow capturing ownership of variables with the move keyword.
Let’s see the most basic example:
fn main() {
let x = 10; // 1. Variable Declaration
// 2. Closure Definition: Captures the environment variable `x`
let add_to_x = |y: i32| -> i32 {
x + y
};
// 3. Calling the Closure with an argument
let result = add_to_x(5);
// 4. Printing the result
println!("The result of adding 5 to {} is: {}", x, result); // Output: 15
}
Explanation:
Variable Declaration: The variable x is initialized with the value 10.
Closure Definition: The closure add_to_x is defined, which captures the variable x from the surrounding environment and adds it to the argument y.
3, Calling the Closure: The closure is invoked with the argument 5, adding it to the captured value x (which is 10), resulting in 15.
- Printing the Result: The program prints the result of adding 5 to x (10), which is 15.