liveBook · Manning

Data transformation

As explained in Learn Rust in a Month of Lunches

map is an iterator adaptor that applies a transformation to each item and returns a new iterator producing the transformed items.

Use `.map()` when you want to turn each item from an iterator into a new item. Give it a closure—a small piece of code that receives one item, such as `|num| num * 2`. The result is another iterator that will produce the transformed items. section 8.2 section 12.1

fn main() {
    let num_vec = vec![2, 4, 6];
 
    let double_vec: Vec<i32> = num_vec   #1
        .iter()                          #2
        .map(|num| num * 2)              #3
        .collect();                      #4
    println!("{:?}", double_vec);
}

Starting with `[2, 4, 6]`, the closure doubles each number. `.collect()` puts the results into a new `Vec<i32>`, which prints as `[4, 8, 12]`. section 8.3.2

Why collect? Iterator `.map()` is lazy: it prepares the transformation but does not run it until the iterator is used. Leaving a mapped iterator unused produces a compiler warning, not a panic. `.collect()` is one way to use it and make a vector. section 8.3.2

Choose how items enter the transformation:

  • `.iter()` supplies references. Mapping them into a new vector leaves the original vector available. section 8.2
  • `.into_iter()` supplies values. After it takes a vector by value, that original vector is no longer available. section 8.2
  • For a different job—changing existing items in place—use `.iter_mut()` with `.for_each()` rather than mapping into a new vector. section 8.2 section 8.3.1

Arrays also have `.map()`. It returns an array of the same length, possibly with a different item type, without a separate `.collect()` call. For example, `[1, 5, 9]` can become an array of strings by mapping each number with `|i| i.to_string()`. section 20.1.2

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains closure inputs, ownership choices, lazy execution, and collection; also shows the generic `FnMut` signature.
Examples
Doubles numbers into a vector, maps borrowed and owned vector items, and converts an array of integers to strings.
What it assumes
Introduces closure syntax while relying on basic vectors and method calls; explains iterator ownership choices alongside their effects.
What you can do after
Apply it via Rust’s `.map()` and `.collect()` to create transformed vectors, or use array `.map()` to produce a new array.
How it connects
Connects map to iterators, closures, collect, ownership, for_each, and array mapping.

Also explained in

Compare how 20 books explain data transformation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.