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.
let squares: Vec<u32> = (1..=4).map(|n| n * n).collect(); let word: String = ['r', 'u', 's', 't'].iter().collect();
Try it
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.
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
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/HashSetiteration 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
partitionor loop manually. - Pre-allocation.
collectreserves capacity fromsize_hint, so exact-size sources (ranges, slices,mapover them) allocate once. Afiltersource grows as it goes. Vec::extendis the append version:v.extend(iter)adds to an existing collection without a new allocation. SeeVec::extendandExtendandFromIterator.- Implement
FromIteratorfor your own type to make it acollecttarget. collect::<String>()fromStringitems concatenates them; it does not insert separators. Usejoinon aVec<String>or slice for that.- Consuming:
collecttakes the iterator by value, so you cannot reuse it afterwards.