Skip to main content

How to Change Each Item of an Iterator with map in Rust

· 7 min read
Jagdish Kumawat
Founder @ Dewiride

names.iter().map(|name| name.to_uppercase()) gives a new iterator whose items are the old ones changed by the closure. map itself does nothing until something consumes that iterator, such as collect(), which builds a Vec from it.

Syntax​

Syntax
let <result>: Vec<T> = <collection>.iter().map(|<item>| <new value>).collect();
PartWhat it does
<collection>.iter()An iterator over the items of a collection, such as a Vec, that borrows them without taking them out.
.map(|<item>| <new value>)A new iterator that gives the closure's result for each item, in the same order.
.collect()Runs the iterator and builds a collection from its items.
Vec<T>The collection to build, where T is the type the closure returns.

The standard library's Iterator::map: "Takes a closure and creates an iterator which calls that closure on each element." The Rust Book, Processing a Series of Items with Iterators: "In Rust, iterators are lazy, meaning they have no effect until you call methods that consume the iterator to use it up."

The Example​

The example has a Vec of three names. It uses map twice, once to turn each name into capitals and once to get each name's length, and collects both results into new Vecs. Then a changed version uses map only to print each name, without collecting anything.

Prerequisites​

  • Rust, with Cargo. This guide uses Rust 1.100.1.

Step 1: Create the Project and Write the Code​

Terminal
cargo new demo
cd demo

cargo new demo creates a project with a src/main.rs. Replace its contents:

src/main.rs, which makes a Vec of the names ada, grace and linus, maps each name to capitals and collects the results into upper, maps each name to its length and collects those into lengths, and prints upper, lengths and names.

src/main.rs
fn main() {
let names = vec!["ada", "grace", "linus"];

let upper: Vec<String> = names.iter().map(|name| name.to_uppercase()).collect();
let lengths: Vec<usize> = names.iter().map(|name| name.len()).collect();

println!("{upper:?}");
println!("{lengths:?}");
println!("{names:?}");
}
  • names.iter() borrows the names, so names can still be printed at the end.
  • .map(|name| name.to_uppercase()) turns each name into a new String in capitals.
  • .map(|name| name.len()) gives each name's length, a usize.
  • .collect() builds the Vec<String> and the Vec<usize> that the variables' types ask for.

Step 2: Run It​

Terminal
cargo run -q
Output
["ADA", "GRACE", "LINUS"]
[3, 5, 5]
["ada", "grace", "linus"]

-q keeps Cargo quiet, so only the program's output shows. The command is the same in zsh, bash and PowerShell.

Step 3: Use map Only to Print​

Replace src/main.rs with a version that prints each name from inside map, and then prints done:

src/main.rs
fn main() {
let names = vec!["ada", "grace", "linus"];

names.iter().map(|name| println!("{}", name.to_uppercase()));
println!("done");
}
Terminal
cargo run -q
Output
warning: `Iterator::map` call that discard the iterator's values
--> src/main.rs:4:18
|
4 | names.iter().map(|name| println!("{}", name.to_uppercase()));
| ^^^^------------------------------------------^
| | |
| | this function returns `()`, which is likely not what you wanted
| | called `Iterator::map` with callable that returns `()`
| after this call to map, the resulting iterator is `impl Iterator<Item = ()>`, which means the only information carried by the iterator is the number of items
|
= note: `Iterator::map`, like many of the methods on `Iterator`, gets executed lazily, meaning that its effects won't be visible until it is iterated
= note: `#[warn(map_unit_fn)]` (part of `#[warn(unused)]`) on by default
help: you might have meant to use `Iterator::for_each`
|
4 - names.iter().map(|name| println!("{}", name.to_uppercase()));
4 + names.iter().for_each(|name| println!("{}", name.to_uppercase()));
|

warning: unused `Map` that must be used
--> src/main.rs:4:5
|
4 | names.iter().map(|name| println!("{}", name.to_uppercase()));
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: iterators are lazy and do nothing unless consumed
= note: `#[warn(unused_must_use)]` (part of `#[warn(unused)]`) on by default
help: use `let _ = ...` to ignore the resulting value
|
4 | let _ = names.iter().map(|name| println!("{}", name.to_uppercase()));
| +++++++

done

A zsh terminal where cargo run -q prints the names in capitals, their lengths 3, 5 and 5 and the names unchanged, then, for the changed file, warns that the Iterator::map call discards the iterator's values and that an unused Map must be used, and prints only done.

What Happened​

  • ["ADA", "GRACE", "LINUS"]: each name changed by the closure, in the same order.
  • [3, 5, 5]: the lengths of ada, grace and linus.
  • ["ada", "grace", "linus"]: names itself didn't change. map made new values.
  • The changed version printed only done. map built an iterator, but nothing consumed it, so the closure never ran. The second warning says why: "iterators are lazy and do nothing unless consumed". The first one suggests for_each for a closure that only does something and returns nothing. Its wording, "call that discard", is the compiler's own, and I reported the typo as Rust issue #166989.

To print each item, use a loop instead. In my check, names.iter().for_each(|name| println!("{}", name.to_uppercase())); printed ADA, GRACE and LINUS, and a for loop over &names that printed name.len() printed 3, 5 and 5.

Common Mistakes​

MistakeWhat happensDo this instead
map only to print, as in names.iter().map(|name| println!("{}", name.to_uppercase()))Nothing is printed, and Rust warns unused `Map` that must be usedUse a for loop, or for_each
map on the Vec itself, as in names.map(...)error[E0599]: no method named `map` found for struct `Vec<&str>` in the current scope, with the help "call .into_iter() first"Call .iter() first
collect() with no type to builderror[E0283]: type annotations neededGive the variable a type, as in let upper: Vec<String>
into_iter() when you still need the Vec afterwardserror[E0382]: borrow of moved value: `names` Use iter(), which borrows the items

Troubleshooting​

SymptomLikely causeFix
warning: `Iterator::map` call that discard the iterator's valuesA closure in map that returns nothingUse for_each, as the help suggests, or a for loop
A closure in map that never runsNothing consumes the iteratorEnd the chain with collect(), sum() or another method that consumes it

FAQ​

Should I use map or a for loop?​

Use map to build new values from old ones, and a for loop to do something with each item. The Iterator::map documentation: "If you're doing some sort of looping for a side effect, it's considered more idiomatic to use for than map()."

Can I add up the results of map?​

Yes, with sum(), which consumes the iterator. For prices of 10, 25 and 40, let total: i32 = prices.iter().map(|price| price * 2).sum(); gave 150.

Conclusion​

map turns each item of an iterator into a new value with a closure, and collect() gathers the results into a Vec. Because iterators are lazy, map alone does nothing: use it to build values, and a for loop to act on each item.

Additional Resources​