DEV Community

Cover image for What are Closures in Rust?
Francesco Ciulla
Francesco Ciulla

Posted on

6 1 1 1 1

What are Closures in Rust?

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
}
Enter fullscreen mode Exit fullscreen mode

Explanation:

  1. Variable Declaration: The variable x is initialized with the value 10.

  2. 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.

  1. Printing the Result: The program prints the result of adding 5 to x (10), which is 15.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free