Collect

Collect in Rust: Hand in a roll of negatives and the darkroom will do exactly as much work as the order form tells it to, and not one step more.

The Analogy: The Order Form At The Darkroom

Hand in a roll of negatives and the darkroom will do exactly as much work as the order form tells it to, and not one step more. The negatives do not imply an outcome. The same roll comes back as a wallet of loose prints, or as a bound album, or as a card index with one print filed under each subject, and nothing whatsoever about the roll decided which of those you get.

So the form has to be filled in, and if you leave the box blank they telephone you rather than guessing. That is the part that irritates everybody the first time. You have handed over everything needed to do the work, and you are still being asked a question -- and the question is not about the work at all, it is about the shape of the thing you want back.

Different boxes cost different amounts and behave differently once ticked. Loose prints are cheapest, because stacking is barely work. The card index costs more, because filing is real work, and it has a property the wallet does not: two negatives of the same subject end up in the same place in the drawer, and the second one quietly displaces the first. That is not the darkroom making a mistake. That is what a card index is.

And there is one box near the bottom of the form that is not about shape at all. It says: if any negative on this roll is damaged, stop work, and send back the damaged negative instead of a set of prints. Tick it and you no longer receive a wallet with a blank in the middle -- you receive either a complete set or a single fault report, one or the other. It is a completely different kind of decision from the ones above it, and it is made in the same place on the same form.


Syntax or Core Structure

collect runs an iterator to the end and builds something out of what came through:

fn main() {
    let readings = vec![18, 24, 7, 31];

    let doubled: Vec<i32> = readings.iter().map(|r| r * 2).collect();
    let labels: Vec<String> = readings.iter().map(|r| format!("r{r}")).collect();
    let joined: String = labels.join(", ");

    println!("{doubled:?}");
    println!("{labels:?}");
    println!("{joined}");

    let backwards: String = "north gate".chars().rev().collect();

    println!("{backwards}");

    let sizes = readings.iter().map(|r| r * 10).collect::<Vec<i32>>();

    println!("{sizes:?}");
}

Output:

[36, 48, 14, 62]
["r18", "r24", "r7", "r31"]
r18, r24, r7, r31
etag htron
[180, 240, 70, 310]

map is the adapter held back from the previous lesson: it hands each item to a closure and yields whatever comes out, lazily and one at a time like everything else. It is collect at the end that makes any of it happen.

Notice that the destination type was written down every single time, in one of two places:

Written asWhere the answer came from
let v: Vec<i32> = it.collect();The annotation on the binding
it.collect::<Vec<i32>>()The turbofish on the call
let v: Vec<_> = it.collect();Container named, element type inferred
fn f() -> Vec<i32> { it.collect() }The function's return type
it.collect() with none of the aboveNowhere: error[E0282]: type annotations needed

The reason is visible in the signature. collect is generic over what it returns and takes no arguments at all:

fn collect<B: FromIterator<Self::Item>>(self) -> B
pub trait FromIterator<A> {
    fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> Self;
}

Every type that can be built from a sequence implements FromIterator, and collect is nothing more than a polite way of calling from_iter. Since the choice of B appears only in the return position, there is nothing at the call site for the compiler to work backwards from -- which is the darkroom's telephone call, in compiler form.


Technical Depth: Choosing What Comes Out

The usual destinations

TargetWhat to know about it
Vec<T>Keeps order, keeps duplicates, one allocation when the length is known in advance
StringFrom char, &str or String items
HashMap<K, V>From (K, V) pairs; a repeated key replaces the earlier value
BTreeMap<K, V>The same, kept sorted by key, so printing it is deterministic
HashSet<T> and BTreeSet<T>Duplicates collapse, so the count can come out smaller than you put in
VecDeque<T>When you will be pushing at both ends afterwards
Box<[T]>A boxed slice, for when the length will never change again
Result<Vec<T>, E>From Result items; stops dead at the first Err
Option<Vec<T>>From Option items; stops dead at the first None
use std::collections::{BTreeMap, BTreeSet};

fn main() {
    let bays = ["A1", "A2", "A3", "A1"];
    let counts = [12, 0, 7, 99];

    let index: BTreeMap<&str, i32> =
        bays.iter().copied().zip(counts.iter().copied()).collect();

    for (bay, n) in &index {
        println!("{bay} {n}");
    }

    let unique: BTreeSet<&str> = bays.iter().copied().collect();

    println!("{} names, {} unique", bays.len(), unique.len());

    let words: Vec<&str> = "north gate  is  open".split_whitespace().collect();

    println!("{words:?}");
}

Output:

A1 99
A2 0
A3 7
4 names, 3 unique
["north", "gate", "is", "open"]

A1 went in twice, with 12 first and 99 last, and the map holds 99. Nothing warned about it and nothing recorded that 12 was ever there. That is the card index behaving as a card index, and it is a data-loss bug in any importer whose author had not thought about it.

The copied() calls are there because bays.iter() yields &&str and the map wants &str. That extra layer of reference is the single most common reason a collect refuses to compile.

The box near the bottom of the form

fn total(input: &[&str]) -> Result<u32, std::num::ParseIntError> {
    let numbers = input
        .iter()
        .map(|s| s.parse::<u32>())
        .collect::<Result<Vec<u32>, _>>()?;

    Ok(numbers.iter().sum())
}

fn main() {
    let good = ["10", "24", "7"];
    let bad = ["10", "two", "7"];

    let a: Result<Vec<u32>, _> = good.iter().map(|s| s.parse::<u32>()).collect();

    println!("{a:?}");

    match bad.iter().map(|s| s.parse::<u32>()).collect::<Result<Vec<u32>, _>>() {
        Ok(v) => println!("ok {v:?}"),
        Err(e) => println!("err {e}"),
    }

    let each: Vec<Result<u32, _>> = bad.iter().map(|s| s.parse::<u32>()).collect();
    let errors = each.iter().fold(0, |acc, r| if r.is_err() { acc + 1 } else { acc });

    println!("items {}  errors {errors}", each.len());
    println!("{:?}", total(&good));

    match total(&bad) {
        Ok(n) => println!("{n}"),
        Err(e) => println!("stopped: {e}"),
    }
}

Output:

Ok([10, 24, 7])
err invalid digit found in string
items 3  errors 1
Ok(41)
stopped: invalid digit found in string

Read the two collect calls on the bad array against each other, because the difference between them is the whole point of this lesson. The iterator chain is identical -- same array, same closure, same parse -- and only the target type differs. Result<Vec<u32>, _> gives you either every value or the first error and nothing else; the item after "two" was never even parsed. Vec<Result<u32, _>> parses all three and keeps all three outcomes, good and bad side by side.

Which one you want is a real decision about your problem, not a stylistic preference. A configuration file where one bad line makes the whole file meaningless wants the first. A batch of a thousand customer records where you intend to import the 997 good ones and report the three bad ones wants the second, and reaching for the first there means your import fails on record four and tells the operator nothing about records five to a thousand.

The ? inside total is Module 5's operator meeting Module 7's pipeline, and collect::<Result<Vec<_>, _>>()? is one of the most-typed sequences in real Rust. Option<Vec<T>> behaves the same way with None in place of Err.

Adding to something that already exists

fn main() {
    let mut all: Vec<u32> = vec![1, 2];

    all.extend([3, 4]);
    all.extend("56".chars().map(|c| c.to_digit(10).unwrap_or(0)));

    println!("{all:?}");
}

Output:

[1, 2, 3, 4, 5, 6]

collect builds a new container; extend pours into one you already have. When the destination exists, extend is the honest way to say so, and it avoids collecting into a temporary Vec only to append it and drop it.

What it costs

A collect into a Vec asks the iterator how many items to expect before it starts, and reserves that much. For a chain of map, enumerate and zip over a slice the answer is exact, so the whole thing is one allocation and no reallocation at all. Adapters that cannot know -- filter is the obvious one, and it is the next lesson -- can only give a range, so the Vec starts at the lower bound and may grow as it fills. Neither case is something to design around at small sizes, and both are worth knowing when the input is large enough that allocation shows up in a profile.


Real World Example: Two Ways To Read The Same Pasted Column

Somebody pastes a block of bay=count lines into a text box. Some of the lines are wrong. There are exactly two sensible things a program can do about that, and both of them are one collect call:

use std::collections::BTreeMap;

fn split<'a>(row: &'a str) -> Result<(&'a str, u32), String> {
    let mut halves = row.splitn(2, '=');

    let key = match halves.next() {
        Some(k) if !k.is_empty() => k,
        _ => return Err(format!("no key in {row:?}")),
    };

    let rest = match halves.next() {
        Some(v) => v,
        None => return Err(format!("no '=' in {row:?}")),
    };

    match rest.trim().parse::<u32>() {
        Ok(n) => Ok((key, n)),
        Err(e) => Err(format!("{key}: {e}")),
    }
}

fn strict<'a>(rows: &[&'a str]) -> Result<BTreeMap<&'a str, u32>, String> {
    rows.iter().copied().map(split).collect()
}

fn lenient<'a>(rows: &[&'a str]) -> (BTreeMap<&'a str, u32>, Vec<String>) {
    let outcomes: Vec<Result<(&'a str, u32), String>> =
        rows.iter().copied().map(split).collect();

    let mut kept = BTreeMap::new();
    let mut problems = Vec::new();

    for outcome in outcomes {
        match outcome {
            Ok((k, v)) => {
                if let Some(old) = kept.insert(k, v) {
                    problems.push(format!("{k}: {v} replaced {old}"));
                }
            }
            Err(e) => problems.push(e),
        }
    }

    (kept, problems)
}

fn main() {
    let clean = ["bay-a=120", "bay-b=45", "bay-c=7"];
    let messy = ["bay-a=120", "bay-b=", "bay-c=four", "bay-a=98", "=5", "bay-d=900"];

    match strict(&clean) {
        Ok(m) => println!("strict clean {m:?}"),
        Err(e) => println!("strict clean refused: {e}"),
    }

    match strict(&messy) {
        Ok(m) => println!("strict messy {m:?}"),
        Err(e) => println!("strict messy refused: {e}"),
    }

    let (kept, problems) = lenient(&messy);

    println!("lenient kept {} of {}", kept.len(), messy.len());

    for (bay, n) in &kept {
        println!("  {bay} {n}");
    }

    for p in &problems {
        println!("  ! {p}");
    }

    let names: Vec<&str> = kept.keys().copied().collect();
    let total: u32 = kept.values().sum();

    println!("names {names:?}");
    println!("total {total}");
}

Output:

strict clean {"bay-a": 120, "bay-b": 45, "bay-c": 7}
strict messy refused: bay-b: cannot parse integer from empty string
lenient kept 2 of 6
  bay-a 98
  bay-d 900
  ! bay-b: cannot parse integer from empty string
  ! bay-c: invalid digit found in string
  ! bay-a: 98 replaced 120
  ! no key in "=5"
names ["bay-a", "bay-d"]
total 998

The two functions begin with the same eight tokens: rows.iter().copied().map(split).collect(), character for character. There is no flag, no branch and no second version of split. strict collects into Result<BTreeMap<_, _>, String> and therefore stops at row two and hands back that one fault, having never looked at rows three to six. lenient collects into Vec<Result<_, _>> and therefore runs all six and keeps all six answers. The behaviour was chosen by a type.

Result<BTreeMap<&str, u32>, String> is also FromIterator composing, and it is worth pausing on. Two separate implementations cooperate without knowing about each other: the one that builds a map out of (K, V) pairs, and the one that lifts a sequence of Results into a single Result wrapped around whatever the successes would have built. Nobody wrote a map-of-results special case. The same pairing gives you Result<String, E>, Option<BTreeSet<T>>, and every other combination you can name.

The line bay-a: 98 replaced 120 is the card-index drawer, caught in the act. bay-a appears twice in the messy input and the map holds 98, so 120 is gone -- and the only reason the report can mention it at all is that insert returns the old value and the code bothered to look. A plain collect straight into a map would have discarded that fact permanently, and kept.len() being 2 rather than 3 would be the only surviving hint that anything happened. Note also that the explicit 'a on all three signatures is not decoration: &[&str] contains two elidable lifetimes, so elision cannot pick one for the returned &str, which is Module 6's rule showing up in ordinary code.

The honest limits are these. split allocates a fresh String for every failure, which is fine for six rows and wasteful for six million; a custom error enum, or Module 5's Box<dyn Error>, is what you would reach for at scale. Because the error type is String, nothing downstream can match on which kind of failure occurred -- the message is for a human and useless to a program. strict reports exactly one fault, so cleaning a file with forty bad rows means forty runs. Neither function reports a row number, and adding one means an enumerate before the map and an index threaded through split. splitn(2, '=') means a value containing = survives intact but a key containing one is silently truncated. And the returned BTreeMap<&str, u32> borrows from the input rows, so it cannot outlive them -- convenient here, and the first thing to change if the map needs to be stored anywhere.


Common Mistakes

  1. Calling collect() with nothing to infer from. let v = it.collect(); produces error[E0282]: type annotations needed, and the fix is never to change the iterator -- it is to say what you want back, on the binding or with a turbofish.
  1. Naming the container but leaving the element ambiguous. let v: Vec<_> = "1 2".split(' ').map(|s| s.parse()).collect(); still fails, because _ cannot tell parse what to parse into. Either write Vec<i32> or write parse::<i32>(); naming the container is only enough when something else already pins the item type.
  1. Confusing Result<Vec<T>, E> with Vec<Result<T, E>>. They are built by the same call and behave oppositely. The first abandons the batch at the first fault; the second processes everything. Writing the first when you wanted a per-row report is a bug that only shows up on messy input.
  1. Collecting into a HashMap and being surprised. Repeated keys silently replace, so the count shrinks with no warning, and iteration order is randomly seeded per run -- so a test that prints a collected HashMap will pass and fail on alternate afternoons.
  1. Collecting into a set and then trusting the count. HashSet and BTreeSet are exactly the tools for collapsing duplicates, which means set.len() is not the number of items that went in. If you needed both figures, keep both.
  1. Collecting in the middle of a chain. it.map(..).collect::<Vec<_>>().into_iter().map(..) allocates a whole vector, walks it once and throws it away. Adapters compose directly; the only reasons to break a chain are needing the values twice or needing the collection itself.
  1. Collecting &&str into a String. String can be built from char, &str and String items, but not from references to references, which is what slice.iter() yields. copied() or cloned() removes the extra layer, and this is the single most common cause of a mysterious FromIterator error message.
  1. Collecting in order to measure. it.collect::<Vec<_>>().len() is it.count() with an allocation attached, and collecting to test emptiness is it.next().is_some() with an allocation attached. If the container is never used again, you did not need it.
  1. Treating collect::<Result<Vec<_>, _>>() as validation. It gives you the first error, not the list of everything wrong, and it stops the iterator there. A validation report needs Vec<Result<_, _>> and a pass over the outcomes.

Best Practices

  • Say what you want back in the smallest place that works: a turbofish when you are in the middle of an expression, an annotation on the let when there is one, and nothing at all when the function's return type already answers the question.
  • Decide between Result<Vec<_>, E> and Vec<Result<_, E>> before you write the chain, by asking whether one bad item invalidates the batch. That is a question about the problem, and the answer is the type you write.
  • Prefer BTreeMap and BTreeSet when the result will be printed, compared or asserted on. Deterministic order costs nothing extra to ask for and saves you a flickering test.
  • Collect once, at the end. Everything upstream should stay lazy so that a chain over a million items still touches each one exactly once.
  • Reach for extend when the destination already exists, rather than collecting a temporary and appending it.
  • Write Vec<_> when the element type is already pinned by something in the chain, and spell it out when it is not. The underscore is a way of saying "you already know this", not a way of avoiding a decision.
  • Let collect do the sizing. A map over a slice knows its exact length, so the result is one allocation; there is no need to build a Vec::with_capacity and push in a loop.
  • Use count, sum, max or any when you want one number or one answer. Collecting into a container you immediately discard is the clearest sign that a consumer was the right tool.

Practice Exercises

  1. Take one chain -- ["A1", "A2", "A3", "A1"].iter().copied() -- and collect it four times: into a Vec<&str>, into a String, into a BTreeSet<&str>, and (after a zip with some counts) into a BTreeMap<&str, u32>. Print the length of each result and write one sentence explaining why the four numbers are not all the same.
  1. Build the two-mode parser from the worked example, then add a println! at the top of split reporting the row it was given. Run both modes on the messy input and use the printed lines to prove that strict never looked at rows three to six.
  1. Change lenient so every message carries a row number, using enumerate before the map and passing the index into split. Keep the strict version working unchanged, and note what had to change in split's signature.
  1. Replace the String error type with an enum with three variants -- missing key, missing separator, unparsable value -- and confirm that collect::<Result<Vec<_>, MyError>>() still compiles without any other change. Explain which FromIterator implementation made that work, and what you can now do at the call site that you could not do with a String.