Skip to main content

How to Collect an Iterator into a Vec in Rust

· 5 min read
Jagdish Kumawat
Founder @ Dewiride

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​

Syntax
let name: Vec<T> = iterator.collect();
let name = iterator.collect::<Vec<T>>();
PartWhat it does
iteratorAnything 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​

Terminal
cargo new demo
cd demo
Output
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:

src/main.rs, which collects the words of red green blue into a Vec of string slices with a type annotation, collects the characters of abc into a Vec of char with the turbofish, prints both, and prints the number of words.

src/main.rs
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 annotation Vec<&str> on words tells collect to build a Vec of 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 the Vec.

Step 3: Run It​

Terminal
cargo run -q
Output
["red", "green", "blue"]
['a', 'b', 'c']
3

A zsh terminal where cargo run -q prints the words red, green and blue in a list, the characters a, b and c in a list, and 3.

cargo run compiles the program and runs it, and -q hides Cargo's own status lines.

What Happened​

  • collect built a Vec of the three words. The debug format, {words:?}, prints each one in double quotes.
  • The second collect built a Vec of characters, which the debug format prints in single quotes.
  • Once collected, the words are a real list: len() counted 3 of them.

Common Mistakes​

MistakeWhat happensDo this instead
No type at all: let words = text.split(' ').collect();error[E0283]: type annotations neededAnnotate 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​

SymptomLikely causeFix
type annotations needed on a line with collectRust can't tell which collection to buildlet 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 itemsMatch 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​