</>
Skip to content
Rust lessons (31/43)

Rust — Closures

Basic closure

fn main() {
    let add = |a, b| a + b;
    println!("{}", add(3, 4)); // 7

    let greet = |name: &str| -> String {
        format!("Hello, {}!", name)
    };
    println!("{}", greet("Alice"));
}

Closure captures

fn main() {
    let name = String::from("Alice");

    // Captures by reference (default)
    let greet = || println!("Hello, {}!", name);
    greet();

    // Captures by value
    let name2 = name.clone();
    let greet2 = move || println!("Hello, {}!", name2);
    greet2();
}

Closure as parameter

fn apply<F: Fn(i32, i32) -> i32>(f: F, a: i32, b: i32) -> i32 {
    f(a, b)
}

fn main() {
    let add = |a, b| a + b;
    let mul = |a, b| a * b;

    println!("Add: {}", apply(add, 3, 4));
    println!("Mul: {}", apply(mul, 3, 4));
}

Fn, FnMut, FnOnce

fn call_fn(f: impl FnOnce()) {
    f(); // Can only be called once
}

fn call_fn_mut(mut f: impl FnMut()) {
    f(); // Can be called multiple times
}

fn call_fn(f: impl Fn()) {
    f(); // Can be called multiple times
}

fn main() {
    let mut count = 0;

    call_fn_mut(|| {
        count += 1;
        println!("Count: {}", count);
    });
}

Mini Practice

Write Rust code that:

  1. Creates a basic closure
  2. Passes a closure to a function
  3. Uses move to capture by value
  4. Demonstrates Fn, FnMut, FnOnce

Up Next

In the next lesson, you'll learn about Smart Pointers — Box, Rc, and RefCell.

Related Topics

Frequently Asked Questions about Closures

What is Closures in Rust?

Closures is a fundamental concept in Rust. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Closures?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Closures.

Why is Closures important in Rust?

Closures is essential for Rust development. Understanding this concept will help you write better code and solve real-world problems more effectively.