How to Change Each Item of an Iterator with map in Rust
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
let <result>: Vec<T> = <collection>.iter().map(|<item>| <new value>).collect();
| Part | What 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
cargo new demo
cd demo
cargo new demo creates a project with a src/main.rs. Replace its contents:

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, sonamescan still be printed at the end..map(|name| name.to_uppercase())turns each name into a newStringin capitals..map(|name| name.len())gives each name's length, ausize..collect()builds theVec<String>and theVec<usize>that the variables' types ask for.
Step 2: Run It
cargo run -q
["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:
fn main() {
let names = vec!["ada", "grace", "linus"];
names.iter().map(|name| println!("{}", name.to_uppercase()));
println!("done");
}
cargo run -q
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

What Happened
["ADA", "GRACE", "LINUS"]: each name changed by the closure, in the same order.[3, 5, 5]: the lengths ofada,graceandlinus.["ada", "grace", "linus"]:namesitself didn't change.mapmade new values.- The changed version printed only
done.mapbuilt 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 suggestsfor_eachfor 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
| Mistake | What happens | Do 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 used | Use 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 build | error[E0283]: type annotations needed | Give the variable a type, as in let upper: Vec<String> |
into_iter() when you still need the Vec afterwards | error[E0382]: borrow of moved value: `names` | Use iter(), which borrows the items |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
warning: `Iterator::map` call that discard the iterator's values | A closure in map that returns nothing | Use for_each, as the help suggests, or a for loop |
A closure in map that never runs | Nothing consumes the iterator | End 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
- Iterator::map, in the Rust standard library documentation.
- Processing a Series of Items with Iterators, in The Rust Programming Language.
- Rust issue #166989, about the wording of the map_unit_fn warning.
