9951 explained code solutions for 126 technologies


rustHow to declare a closure in Rust


A closure in Rust is declared using the |parameters| expression syntax. The parameters are the values that are passed into the closure, and the expression is the code that is executed when the closure is called. For example, the following code declares a closure that takes two parameters and returns the sum of them:

let add_two_numbers = |x: i32, y: i32| x + y;

The closure can then be called by passing in the appropriate parameters:

let result = add_two_numbers(2, 3);

The result of this call will be 5. Closures can also be used to capture variables from the surrounding scope, allowing them to be used within the closure. For example:

let x = 5;
let add_x = |y: i32| x + y;

In this example, the closure add_x will always add x to its parameter, regardless of what x is set to in the surrounding scope.

Helpful links

Edit this code on GitHub