liveBook · Manning

Data transformation

As explained in Idiomatic Rust

map is an iterator or result-like-type method that applies a function to each available value and returns the transformed result.

Use map to apply a function or closure to each iterator item, or to transform a present Option or Result value. Iterator map returns another iterator and evaluates lazily; collect forces evaluation and may need a target type annotation. section 3.2.5 section 10.3

let arr = [1, 2, 3, 4];
println!("{:?}", arr);
let vec: Vec<_> = arr.iter().map(|v| v.to_string()).collect();
println!("{:?}", vec);

This example converts array elements to strings, then collects the transformed iterator into a vector. section 3.2.5

Transforming parsed values

Parsing strings with map produces Result values, so partition can separate successful parses from errors without discarding either. By contrast, flat_map flattens each Result into an iterator: an Ok contributes its value, while an Err contributes nothing. section 3.2.5 section 3.2.5

For Option and Result, map transforms the contained value only when it is present or successful; None and Err pass through unchanged. Prefer this to unwrap when transforming a value without needing to handle failure by panicking. section 10.3 section 10.10

How Idiomatic Rust covers it

How deep it goes
Defines map's closure signature and laziness, then demonstrates collection and Result handling without implementing the iterator.
Examples
Demonstrates converting integers to strings, parsing strings, and transforming ranked dog-breed entries.
What you can do after
Apply map to transform iterator items or present Option and Result values, then collect or chain the results.
How it connects
Connects iterators with closures, collect, flat_map, Result, Option, and error handling.

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 Idiomatic Rust. The section links point to the parts of the book it draws on.