[Avg. reading time: 5 minutes]

Closures

Closures in Rust are anonymous functions that you can store in variables, pass as arguments, and return from other functions.

Think of them as inline, lightweight functions with memory of their environment.

|args| -> return_type { body }

// Simple Closure Example

fn main() {
    let example = |num| -> i32 { num + 1 };
    println!("{}", example(5));
}

Function vs. Closure

// Function vs Closure

fn add_one_fn(x: i32) -> i32 {
    1 + x
}

fn main() {
    //let y = 6;
    let add_one_cl = |x: i32| -> i32 { 1 + x};
    println!("Closure : {}", add_one_cl(3));
    println!("Function : {}", add_one_fn(3));
}
  • Functions are named and reusable
  • Closures are inline and flexible
  • Closures can capture variables from scope. Functions cannot
// Closure returns a value

fn main() {
    let s = String::from("Hello");

    let closure = |name: String| -> String {
        format!("{}, {}!", s, name)
    };

    let result = closure(String::from("Rachel"));
    println!("The result is: {}", result);
}
  • s is not passed as a parameter
  • Closure captures it automatically
  • This is where closures become powerful
// Mutable Values inside Closure

fn main() {
    let plus_two = |x| {
        let mut result: i32 = x;

        result += 1;
        result += 1;

        result
    };

    println!("{}", plus_two(2));
}

Use Cases

  • Pass logic into functions (map, filter, fold)
  • Customize behavior without creating new functions
  • Inline transformations in data pipelines
  • Event handling / callbacks
  • Building higher-order functions

Overall, closures are a very useful tool in Rust, and they can be used to solve a wide range of problems in your code.

#closures #inlineVer 2.0.22

Last change: 2026-04-01