Skip to content

Rust Closures and Iterators — Anonymous Functions, Capturing, and Iterator Adapters

DodaTech Updated 2026-06-28 1 min read

In this tutorial, you will learn about Rust Closures and Iterators. We cover key concepts, practical examples, and best practices to help you master this topic.

Rust closures are anonymous functions with || syntax capturing environment by reference or value, and iterators provide lazy chainable data processing.

What You'll Learn

  • Closure syntax and types
  • Capturing environment
  • Iterator trait and adapters
  • Lazy evaluation

Why It Matters

Closures and iterators enable Functional Programming. DodaZIP uses iterators for file processing pipelines. Firefox uses closures for event handling.

Real-World Use

Data transformation pipelines, event callbacks, sorting/comparison, lazy evaluation chains.

fn main() {
    // Closures
    let add_one = |x: i32| -> i32 { x + 1 };
    println!("{}", add_one(5));

    let add_two = |x| x + 2;  // Type inference
    println!("{}", add_two(5));

    let x = 10;
    let print_x = || println!("x = {}", x);  // Captures by reference
    print_x();

    let mut count = 0;
    let mut increment = || { count += 1; };
    increment();
    increment();
    println!("Count: {}", count); // 2

    // Iterators
    let numbers = vec![1, 2, 3, 4, 5];

    let doubled: Vec<i32> = numbers.iter()
        .map(|x| x * 2)
        .collect();
    println!("{:?}", doubled);

    let sum: i32 = numbers.iter()
        .filter(|x| *x % 2 == 0)
        .map(|x| x * x)
        .sum();
    println!("Sum of squares of evens: {}", sum);

    let found = numbers.iter().find(|&&x| x == 3);
    println!("Found: {:?}", found);

    let any_greater = numbers.iter().any(|&x| x > 10);
    println!("Any > 10: {}", any_greater);
}

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro