Iterators in Rust

From the Rust cheat sheet ยท Collections & Iterators ยท verified Jul 2026

Iterators

Transform collections with iterator adaptors and consumers.

rust
let nums = vec![1, 2, 3, 4, 5];

// Map, filter, collect
let doubled: Vec<i32> = nums.iter().map(|x| x * 2).collect();
let evens: Vec<&i32> = nums.iter().filter(|x| *x % 2 == 0).collect();

// Chaining
let result: i32 = nums.iter()
    .filter(|x| *x % 2 != 0)
    .map(|x| x * x)
    .sum();
๐Ÿ’ก Iterators are lazy โ€” .map() and .filter() do nothing until you .collect() or .sum()
โšก .iter() borrows, .into_iter() consumes, .iter_mut() mutably borrows the collection
๐Ÿ“Œ Use turbofish ::<Vec<_>> with .collect() when the compiler can't infer the target type
๐ŸŸข Chain adaptors freely โ€” Rust optimizes iterator chains to be as fast as hand-written loops
iteratorsmapfiltercollect

More Rust tasks

Back to the full Rust cheat sheet