skip to content

In Rust, why does `let codes = iter.collect();` fail with E0283, and how does `collect` choose between a Vec, a HashSet and a HashMap?

level: middleimportance: must knowfreq 75%

answer

  1. generic return type
  2. FromIterator of the item
  3. annotation or turbofish
  4. Vec<_> infers the element

basics

~20 s

collect is generic over its return type, bounded by FromIterator of the item type, so rustc must learn that type from an annotation, a turbofish or the surrounding code. The chosen type's FromIterator impl decides what gets built.

solid answer

~40 s

The signature is `fn collect<B: FromIterator<Self::Item>>(self) -> B`. Nothing in the call fixes `B`, so `let codes = it.collect();` stops with `error[E0283]: type annotations needed` and the note that the type must implement `FromIterator<u16>`. You name `B` by annotating the binding (`let codes: Vec<u16>`), with a turbofish (`collect::<Vec<_>>()`), or by returning the value from a function whose return type says it; `_` lets the element type be inferred. The target then defines the meaning: `Vec<T>` keeps order and duplicates, `HashSet<T>` keeps one of each, `String` concatenates `char`s or `&str`s, and `HashMap<K, V>` takes `(K, V)` pairs and keeps a single value per key — it does not add values for a repeated key.

code

rust · 25 lines
rust
use std::collections::{HashMap, HashSet};

fn main() {
    let lines = ["ERROR auth 500", "ERROR web 503", "ERROR auth 502"];

    // 1. annotate the binding
    let codes: Vec<u16> = lines
        .iter()
        .filter_map(|l| l.rsplit(' ').next()?.parse().ok())
        .collect();

    // 2. turbofish on collect
    let unique = codes.iter().copied().collect::<HashSet<u16>>();

    // 3. (K, V) pairs into a HashMap: a repeated key keeps one value
    let by_service: HashMap<&str, u16> = lines
        .iter()
        .map(|l| {
            let mut f = l.split(' ').skip(1);
            (f.next().unwrap(), f.next().unwrap().parse().unwrap())
        })
        .collect();

    println!("{codes:?} unique={} services={}", unique.len(), by_service.len());
}

go deeper

for a junior

Recall that collect needs a target type and show both fixes: an annotation on the let binding and a turbofish like collect::<Vec<_>>().

for a middle

Explain the FromIterator bound on collect's return type, why _ is allowed inside the target, and that each target's impl decides deduplication, ordering or concatenation.

for a senior

Catch the semantic traps in review: a HashMap built from pairs silently drops repeated keys, a String target concatenates without separators, and an early collect forces an allocation the next stage may not need.

for a principal

Set a team habit of naming collection targets for their semantics, such as a set for uniqueness and a sorted set for order, so intent is visible in the type rather than in comments.

## The signature that needs a type `Iterator::collect` is declared as: ```rust fn collect<B: FromIterator<Self::Item>>(self) -> B ``` The type parameter `B` appears only in the return type. The iterator fixes `Self::Item` — say `u16` status codes parsed from log lines — but many types can be built from `u16`s, so the call alone leaves `B` open. rustc reports: ```plaintext error[E0283]: type annotations needed = note: the type must implement `FromIterator<u16>` help: consider giving `codes` an explicit type ``` **`FromIterator<A>`** is the std trait with one method, `from_iter`, that builds a value from anything that turns into an iterator of `A`. `collect` simply calls `B::from_iter(self)`. ## Three ways to name the target 1. **Annotate the binding:** `let codes: Vec<u16> = it.collect();` 2. **Turbofish on the call:** `it.collect::<Vec<u16>>()` — useful mid-chain, where there is no binding to annotate. 3. **Let the context decide:** returning the value from `fn codes(..) -> Vec<u16>`, or passing it to a parameter of a concrete type. In all three, `_` can stand for the parts rustc can already infer: `Vec<_>` or `HashSet<_>` let the element type come from the iterator. You still must name the outer type; `collect::<Vec>()` fails with E0107, missing generics for struct `Vec`. ## What each target does The target's `FromIterator` impl is the behaviour you get: | Target | Item type it accepts | What it builds | |---|---|---| | `Vec<T>` | `T` | Every item, in order, duplicates kept | | `HashSet<T>` | `T` (needs `Eq + Hash`) | One copy of each distinct item, no order | | `BTreeSet<T>` | `T` (needs `Ord`) | Distinct items in sorted order | | `String` | `char`, `&str`, `String` | All pieces concatenated, with no separator | | `HashMap<K, V>` | `(K, V)` | One entry per distinct key | Two of these rows surprise people: - `"a-b".split('-').collect::<String>()` is `"ab"`: the pieces are joined with nothing between them. - Collecting `(service, code)` pairs into a `HashMap` does **not** total anything. std's documentation says that when pairs share a key, all but one of the values are dropped. If you need per-key totals, fold into the map or loop with the Entry API (covered with HashMap). Collecting an iterator of `Result` values into `Result<Vec<T>, E>` is another `FromIterator` impl; it belongs to the material on `Option` and `Result`. ## A worked example In the log analyser below, the same lines feed three targets. The `Vec` keeps three codes, the `HashSet` sees three distinct codes, and the `HashMap` has only two entries because `auth` appears twice: ```rust let codes: Vec<u16> = lines.iter() .filter_map(|l| l.rsplit(' ').next()?.parse().ok()) .collect(); let unique = codes.iter().copied().collect::<HashSet<u16>>(); ``` Note that `parse()` itself has a generic return type; here rustc infers `u16` from the annotation on `codes`, flowing backwards through `filter_map`. One annotation at the end of a chain often fixes several inner inference points. ## Errors you will meet - **E0283, type annotations needed** — no target named at all. - **E0277** — the target cannot be built from this item type, for example `collect::<u16>()` on an iterator of `u16`, or a `HashMap` from items that are not pairs. rustc says a value of that type cannot be built from an iterator over elements of the item type. - **E0107** — a turbofish that names `Vec` without its generic argument. - **E0562** — trying `let x: impl Iterator<Item = u16> = ...`; `impl Trait` is not allowed in the type of a variable binding. ## Choosing well - Collect only when you need the collection; if the next step is another pass, keep the iterator lazy. - Pick the target for its semantics, not by habit: a `HashSet` deduplicates for free, a `BTreeSet` sorts for free. - Prefer one annotation at the binding over turbofish on every call; reach for turbofish when the value is used inline. - To add items to a collection you already have, call `extend` (the `Extend` trait) instead of collecting a new one and appending it; `codes.extend(more.iter().filter_map(parse_code))` reuses the existing allocation. (`Iterator::collect_into` does the same from the iterator side but is still unstable.) - When the size is known, `collect` into a `Vec` can use the iterator's size hint to allocate once, so collecting is usually no slower than a hand-written push loop.

  • Why does `collect::<Vec<_>>()` compile while `collect::<Vec>()` does not?
    A turbofish names a type, and `Vec` alone is a generic struct missing its parameter, so rustc reports E0107, missing generics for struct `Vec`. Writing `Vec<_>` supplies a placeholder that inference fills from the iterator's `Item`, which is all `collect` needs.
  • What happens when `(service, code)` pairs with a repeated service are collected into a `HashMap<&str, u16>`?
    The map ends up with one entry per service. std documents that when pairs share a key, all but one of the values are dropped, so nothing is summed or kept as a list. For totals, fold into the map and add through the Entry API; for every value, collect into `HashMap<&str, Vec<u16>>` by hand.
  • Why can one annotation on the binding fix a `parse()` call deep inside the chain?
    Type inference works across the whole expression. Annotating `let codes: Vec<u16>` fixes `B` for `collect`, which fixes the iterator's `Item` as `u16`, which fixes the `Option<u16>` returned by the `filter_map` closure, which fixes `parse::<u16>()`. A turbofish on `parse` would work too; one annotation is usually enough.

  • collect always returns a Vec unless told otherwise
  • Collecting pairs into a HashMap sums values for repeated keys
  • collect::<Vec>() is fine because the element type is obvious
  • Collecting chars or &str into a String inserts spaces between pieces
  • The E0283 error means the iterator's item type is unknown