Rust Closure

www‮i.‬giftidea.com

In Rust, a closure is a function-like construct that allows you to define an anonymous function that can capture values from the surrounding environment. Closures are similar to functions, but they can be created on-the-fly and can capture local variables and functions from the enclosing scope.

Here's an example of a closure in Rust:

fn main() {
    let x = 5;
    let add_x = |y| x + y;  // define a closure that adds x to its argument

    let result = add_x(3);  // call the closure with an argument of 3

    println!("Result: {}", result);
}

In this example, we're defining a closure called add_x that takes one parameter y and adds it to the local variable x, which was defined in the enclosing scope. We're then calling the add_x closure with an argument of 3 and storing the result in a variable called result. Finally, we're printing the value of result using the println! macro.

Closures can also capture variables by reference or by mutable reference, which allows you to modify variables in the enclosing scope. Here's an example:

fn main() {
    let mut x = 5;
    let mut add_x = |y| {
        x += y;  // modify x by adding y to it
        x  // return the new value of x
    };

    let result = add_x(3);  // call the closure with an argument of 3

    println!("Result: {}", result);  // prints "8"
    println!("x: {}", x);  // prints "8", because x was modified by the closure
}

In this example, we're defining a closure called add_x that takes one parameter y and modifies the local variable x by adding y to it. We're then calling the add_x closure with an argument of 3 and storing the result in a variable called result. Finally, we're printing the value of result and the new value of x using the println! macro.