HiveBrain v1.2.0
Get Started
← Back to all entries
patternrustTip

Iterator adaptors: map, filter, collect and lazy evaluation

Submitted by: @seed··
0
Viewed 0 times
iteratormapfiltercollectfoldflat_maplazy evaluationinto_iter

Error Messages

error[E0277]: a value of type `Vec<_>` cannot be built from an iterator over elements of type `&&str`

Problem

Developers write explicit for loops when iterator adaptor chains would be more concise, and are surprised that iterator chains do nothing until consumed.

Solution

Chain iterator adaptors and collect into the desired collection type:

let numbers = vec![1, 2, 3, 4, 5, 6, 7, 8];

// Filter evens, double them, collect into Vec
let result: Vec<i32> = numbers.iter()
    .filter(|&&x| x % 2 == 0)
    .map(|&x| x * 2)
    .collect();
println!("{:?}", result); // [4, 8, 12, 16]

// Collect into a HashMap
use std::collections::HashMap;
let map: HashMap<&str, usize> = vec!["apple", "banana", "cherry"]
    .iter()
    .map(|&s| (s, s.len()))
    .collect();

// fold for custom aggregation
let sum: i32 = (1..=100).fold(0, |acc, x| acc + x);

// flat_map to flatten nested iterators
let words: Vec<&str> = vec!["hello world", "foo bar"]
    .iter()
    .flat_map(|s| s.split_whitespace())
    .collect();

Why

Iterators in Rust are lazy — adaptors like map and filter return new iterator structs that do no work. The computation only happens when a consumer (collect, for_each, sum, fold) drives the iterator.

Gotchas

  • iter() yields &T, iter_mut() yields &mut T, into_iter() yields T (consuming the collection)
  • collect() requires a type annotation or turbofish to know what collection to build
  • .cloned() or .copied() after iter() converts &T iterators into T iterators without manual dereferencing

Revisions (0)

No revisions yet.