12.2 Using Closures

Once defined, closures are called just like named functions. This section introduces some common closure usage patterns.

12.2.1 Calling Closures

fn main() {
    let greet = |name| println!("Hello, {}!", name);
    greet("Alice");
}

12.2.2 Closures with Type Inference

In many scenarios, Rust’s compiler can infer parameter and return types automatically:

fn main() {
    let add_one = |x| x + 1;  // Inferred to i32 -> i32 (once used)
    println!("Result: {}", add_one(5)); // 6
}

Once the compiler infers a type for a closure, you cannot later call it with a different type.

12.2.3 Closures with Explicit Types

When inference fails or if clarity matters, you can specify types:

fn main() {
    let multiply = |x: i32, y: i32| -> i32 {
        x * y
    };
    println!("Result: {}", multiply(6, 7)); // 42
}

12.2.4 Closures Without Parameters

A closure that takes no arguments uses empty vertical pipes (||):

fn main() {
    let say_hello = || println!("Hello!");
    say_hello();
}