Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Iterators

Iterator collect

Reference for Iterator::collect in Rust: building Vec, String, HashMap, HashSet and more from iterators, collecting into Result or Option, and type annotations.

collect() consumes an iterator and builds a collection from its items. It is generic over the result: the same call produces a Vec, a String, a HashMap, a HashSet or any other type that implements FromIterator. Because the compiler cannot guess which one you want, you almost always tell it with a type annotation on the variable or with the turbofish: collect::<Vec<_>>().

Two special cases make collect especially useful. Collecting an iterator of Result<T, E> into Result<C, E> stops at the first error, and collecting Option<T> items into Option<C> stops at the first None. Collecting into () just runs the iterator.

Rust
let squares: Vec<u32> = (1..=4).map(|n| n * n).collect();
let word: String = ['r', 'u', 's', 't'].iter().collect();

Try it

Rust Many target types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust Collecting Result and Option

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
fn collect<B: FromIterator<Self::Item>>(self) -> B;
Name Description
B The collection to build. Chosen by a type annotation, the turbofish or the function's return type.

Returns: a value of type B.

Common FromIterator implementations:

Items Target
T Vec<T>, VecDeque<T>, BTreeSet<T>, HashSet<T>, BinaryHeap<T>, LinkedList<T>, Box<[T]>, Rc<[T]>, Arc<[T]>
(K, V) HashMap<K, V>, BTreeMap<K, V>
char, &char, &str, String, Box<str>, Cow<str> String
Result<T, E> Result<C, E> where C: FromIterator<T>
Option<T> Option<C> where C: FromIterator<T>
() ()

Usage notes

  • Type inference. collect::<Vec<_>>() lets the compiler infer the element type while you choose the container. If it still reports "type annotations needed", the container is the missing piece.
  • Keys in maps and sets. Duplicates are not an error: later items overwrite earlier ones in a map, and sets keep one copy. HashMap/HashSet iteration order is unspecified, so sort before printing.
  • Result collection short-circuits and drops what was collected so far. If you want to keep the good items and the errors, use partition or loop manually.
  • Pre-allocation. collect reserves capacity from size_hint, so exact-size sources (ranges, slices, map over them) allocate once. A filter source grows as it goes.
  • Vec::extend is the append version: v.extend(iter) adds to an existing collection without a new allocation. See Vec::extend and Extend and FromIterator.
  • Implement FromIterator for your own type to make it a collect target.
  • collect::<String>() from String items concatenates them; it does not insert separators. Use join on a Vec<String> or slice for that.
  • Consuming: collect takes the iterator by value, so you cannot reuse it afterwards.