Iterators and Closures in Rust

 

What are Iterators? 

An iterator in Rust is like an automatic conveyor belt  that processes elements one at a time. It helps you traverse, filter, map, and consume data efficiently.

Creating an Iterator

fn main() {
    let numbers = vec![1, 2, 3, 4, 5];
    let mut iter = numbers.iter();
    
    println!("First element: {:?}", iter.next()); // Some(1)
    println!("Second element: {:?}", iter.next()); // Some(2)
}

 .iter() returns an iterator reference.next() moves to the next element (returns None when exhausted).

Transforming Data with Iterators 

Iterators have cool methods like .map() and .filter() for functional programming magic! 🪄

fn main() {
    let numbers = vec![1, 2, 3, 4, 5];
    let doubled: Vec<i32> = numbers.iter().map(|x| x * 2).collect();
    println!("Doubled: {:?}", doubled);
}

 .map(|x| x * 2) transforms each element.  .collect() turns an iterator into a Vec.

What are Closures? 

A closure is like a mini-function  that can capture variables from its environment.

Defining a Closure

fn main() {
    let add = |a, b| a + b; // Closure
    println!("Sum: {}", add(5, 3));
}

 Closures use | instead of fn().  They capture variables from their surrounding scope!

Using Closures in Iterators 

Closures and iterators go hand-in-hand like peanut butter and jelly! 

fn main() {
    let numbers = vec![1, 2, 3, 4, 5];
    let even_numbers: Vec<i32> = numbers.into_iter().filter(|x| x % 2 == 0).collect();
    println!("Even numbers: {:?}", even_numbers);
}

 .filter(|x| x % 2 == 0) keeps even numbers only.into_iter() moves ownership.

When to Use Iterators & Closures? 

  • Use iterators for cleaner loops and lazy evaluation.
  • Use closures for short, flexible functions.


Post a Comment

0 Comments