Logo

Developer learning path

Rust

Closures in Rust

Closures

0

#description

Closures are a feature of Rust that allow you to define anonymous functions, also known as lambda or function literals. Closures can capture values from their enclosing scope and return those values for later use. This makes them very useful for writing expressive and flexible code.

In Rust, closures have a type that is determined by the types of the variables they capture. This means that closures can be used in a type-safe way, without having to explicitly specify the types of the variables involved.

Closures can be defined using the || syntax.

For example, here is a closure that takes a single integer argument and adds 42 to it:

                    
let add_42 = |x: i32| x + 42;
                  

Here, the vertical bars | indicate the start and end of the closure, and the x: i32 specifies the type of the argument. The closure itself consists of a single expression, x + 42.

Closures can also capture variables from their enclosing scope.

For example, consider the following code:

                    
fn main() {
    let greeting = "Hello";
    let add_greeting = |name| format!("{} {}", greeting, name);
    println!("{}", add_greeting("Bob"));
}
                  

Here, we define a closure that captures the greeting variable from the enclosing main function. When we call the closure with the argument "Bob", it returns the string "Hello Bob", which is printed to the console.

In summary, closures are a powerful feature of Rust that allow you to define anonymous functions that can capture variables from their enclosing scope. They can be used in a type-safe way and are very useful for writing expressive and flexible code.

March 27, 2023

If you don't quite understand a paragraph in the lecture, just click on it and you can ask questions about it.

If you don't understand the whole question, click on the buttons below to get a new version of the explanation, practical examples, or to critique the question itself.