How to Collect an Iterator into a Vec in Rust
Many Rust methods, such as split and chars, don't return a list: they return an iterator that hands out items one at a time. collect takes all of them and builds a collection, such as a Vec, as long as you tell it which one.
Syntax
let name: Vec<T> = iterator.collect();
let name = iterator.collect::<Vec<T>>();
| Part | What it does |
|---|---|
iterator | Anything that produces items one at a time, such as text.split(' ') or text.chars(). |
.collect() | Takes every item and builds a collection from them. |
Vec<T> | The collection to build: a Vec of items of type T. Write _ for T to let Rust work the item type out. |
let name: Vec<T> | One way to name the collection: a type annotation on the variable. |
::<Vec<T>> | The other way: the turbofish, right in the call. |
The documentation for Iterator::collect: "Transforms an iterator into a collection." And: "The iterator itself carries no knowledge of the eventual container; the target collection is chosen entirely by the type you ask collect() to return." That is why one of the two ways is needed.
The Example
The example splits red green blue at each space and collects the words with a type annotation, collects the characters of abc with the turbofish, and prints how many words there are.
Prerequisites
- Rust, installed with rustup, which comes with Cargo. This guide uses Rust 1.100.1.
Step 1: Create a Project
cargo new demo
cd demo
Creating binary (application) `demo` package
note: see more `Cargo.toml` keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
cargo new demo creates a folder named demo with a Cargo.toml file, which describes the project, and src/main.rs, which holds the code. cd demo moves into it.
Step 2: Write the Code
Replace the contents of src/main.rs with:

fn main() {
let words: Vec<&str> = "red green blue".split(' ').collect();
println!("{words:?}");
let letters = "abc".chars().collect::<Vec<char>>();
println!("{letters:?}");
println!("{}", words.len());
}
"red green blue".split(' ')is an iterator over the words. The annotationVec<&str>onwordstellscollectto build aVecof string slices."abc".chars()is an iterator over the characters.collect::<Vec<char>>()names the type in the call instead.words.len()is the number of items in theVec.
Step 3: Run It
cargo run -q
["red", "green", "blue"]
['a', 'b', 'c']
3

cargo run compiles the program and runs it, and -q hides Cargo's own status lines.
What Happened
collectbuilt aVecof the three words. The debug format,{words:?}, prints each one in double quotes.- The second
collectbuilt aVecof characters, which the debug format prints in single quotes. - Once collected, the words are a real list:
len()counted 3 of them.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
No type at all: let words = text.split(' ').collect(); | error[E0283]: type annotations needed | Annotate the variable, or add the turbofish |
Collecting &str pieces into Vec<String> | error[E0277]: a value of type `Vec<String>` cannot be built from an iterator over elements of type `&str` | Collect into Vec<&str>, or add .map(String::from) before .collect() |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
type annotations needed on a line with collect | Rust can't tell which collection to build | let name: Vec<_> = ... or .collect::<Vec<_>>() |
cannot be built from an iterator over elements of type `&str` | The item type in Vec<T> doesn't match the iterator's items | Match the items, or convert them with .map first |
FAQ
What does Vec<_> mean?
_ asks Rust to work out the item type from the iterator. "x y".split(' ').collect::<Vec<_>>() gave ["x", "y"], a Vec<&str>.
Can collect build something other than a Vec?
Yes, any type that can be built from the items. A String can be built from characters: "abc".chars().rev().collect::<String>() gave cba.
Annotation or turbofish?
They do the same job. The annotation reads well when you store the result in a variable; the turbofish fits in the middle of a chain of calls.
Conclusion
collect() turns an iterator into a collection, and the type you give it decides which one: let name: Vec<T> = iterator.collect(); or iterator.collect::<Vec<T>>(). When the compiler says "type annotations needed", give it one of the two.
Additional Resources
- Iterator::collect, in the standard library documentation.
