[Avg. reading time: 3 minutes]
Map and Collect
Map: The map function is used to transform elements of an iterator. It takes a closure and applies this closure to each element of the iterator, producing a new iterator with the transformed elements.
- Takes a closure
- Applies transformation lazily
- Returns another iterator
Collect: The collect function is used to transform an iterator into a collection, such as a Vec, HashMap, or HashSet. It consumes the iterator and returns the new collection.
- Consumes iterator
- Produces concrete collection
fn main() { let numbers = vec![1, 2, 3, 4, 5]; let doubled: Vec<i32> = numbers.iter().map(|x| x * 2).collect(); println!("{:?}", doubled); }
- map() does NOT execute immediately
- It returns a lazy iterator
- Nothing happens until you consume it
fn main() { let names = vec!["rachel", "ross", "joey"]; let upper: Vec<String> = names .iter() .map(|name| name.to_uppercase()) .collect(); println!("{:?}", upper); }
Map + Filter
fn main() { let numbers = vec![1, 2, 3, 4, 5]; let result: Vec<i32> = numbers .iter() .map(|x| x * 2) .filter(|x| *x > 5) .collect(); println!("{:?}", result); }