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

Rust — Iterators

Iterator trait

struct Counter {
    count: u32,
}

impl Counter {
    fn new() -> Counter {
        Counter { count: 0 }
    }
}

impl Iterator for Counter {
    type Item = u32;

    fn next(&mut self) -> Option<u32> {
        if self.count < 5 {
            self.count += 1;
            Some(self.count)
        } else {
            None
        }
    }
}

fn main() {
    let counter = Counter::new();
    for n in counter {
        print!("{} ", n);
    }
    println!();
}

Iterator adaptors

fn main() {
    let nums = vec![1, 2, 3, 4, 5];

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

    // filter
    let evens: Vec<&i32> = nums.iter().filter(|&&x| x % 2 == 0).collect();
    println!("Evens: {:?}", evens);

    // zip
    let names = vec!["Alice", "Bob"];
    let ages = vec![30, 25];
    let people: Vec<_> = names.iter().zip(ages.iter()).collect();
    println!("People: {:?}", people);
}

Consuming adaptors

fn main() {
    let nums = vec![1, 2, 3, 4, 5];

    // sum
    let sum: i32 = nums.iter().sum();
    println!("Sum: {}", sum);

    // fold
    let product: i32 = nums.iter().fold(1, |acc, &x| acc * x);
    println!("Product: {}", product);

    // any, all
    let has_even = nums.iter().any(|&x| x % 2 == 0);
    let all_positive = nums.iter().all(|&x| x > 0);
    println!("Has even: {}, All positive: {}", has_even, all_positive);
}

Chaining

fn main() {
    let nums = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

    let result: Vec<i32> = nums
        .iter()
        .filter(|&&x| x % 2 == 0)
        .map(|&x| x * x)
        .take(3)
        .collect();

    println!("{:?}", result); // [4, 16, 36]
}

Mini Practice

Write Rust code that:

  1. Implements the Iterator trait
  2. Uses map and filter adaptors
  3. Chains multiple adaptors
  4. Uses fold to accumulate a value

Up Next

In the next lesson, you'll learn about Closures — anonymous functions.

Related Topics

Frequently Asked Questions about Iterators

What is Iterators in Rust?

Iterators 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 Iterators?

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 Iterators.

Why is Iterators important in Rust?

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