Iterator (Rust)

An iterator produces a sequence of values one at a time via its next() method. Rust iterators are lazy and zero-cost — chains of map/filter/etc. compile to code as fast as a hand-written loop.

Rust

Any type implementing the Iterator trait yields items by repeatedly calling next() until it returns None. You usually get one from .iter() (borrowing), .iter_mut() (mutable borrow), or .into_iter() (taking ownership) on a collection.

Iterators are lazy: adapters like .map(), .filter(), .take(), and .zip() build a new iterator without doing any work. Nothing runs until a consuming method — .collect(), .sum(), .count(), .for_each(), or a for loop — drives it to completion.

Thanks to monomorphization and inlining, these high-level chains are 'zero-cost abstractions': the compiler turns them into the same machine code as an equivalent manual loop. This lets Rust be both expressive and fast.

Syntax

let total: i32 = (1..=5).filter(|n| n % 2 == 1).sum();

Examples

Rust

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

Output:

[2, 4, 6]

Learn it in a lesson

See also

Back to the Dictionary