liveBook · Manning

Collect

As explained in Learn Rust in a Month of Lunches

collect is a Rust iterator method that gathers produced items into a collection or another type inferred or specified by the program.

`.collect()` uses the items produced by an iterator to make another value, often a `Vec`. This matters because methods such as `.map()` are lazy: they prepare work, but do not run it until the iterator is consumed. Calling `.collect()` is one way to consume it. section 8.3.2 section 8.4

fn main() {
    let num_vec = vec![2, 4, 6];
 
    let double_vec: Vec<i32> = num_vec   #1
        .iter()                          #2
        .map(|num| num * 2)              #3
        .collect();                      #4
    println!("{:?}", double_vec);
}

Here, `.iter()` reads the numbers, `.map()` describes how to double each one, and `.collect()` makes `double_vec`. The declared type, `Vec<i32>`, tells Rust what to collect into. section 8.3.2

You can also specify the result type at the call, as in `.collect::<Vec<i32>>()`. Without a consuming step, an unused `.map()` chain produces a compiler warning rather than doing the intended work. section 8.2 section 8.3.2

use std::collections::HashMap;
 
fn main() {
    let some_keys = vec![0, 1, 2, 3, 4, 5];
    let some_values = vec!["zero", "one", "two", "three", "four", "five"];
 
    let number_word_hashmap = some_keys
        .into_iter()                     #1
        .zip(some_values.into_iter())    #2
        .collect::<HashMap<_, _>>();
 
    println!(
        "The value at key 2 is: {}",
        number_word_hashmap.get(&2).unwrap()
    );
}

A `Vec` is not the only destination. This example pairs items from two vectors with `.zip()`, then uses `.collect::<HashMap<_, _>>()` to build a `HashMap`. section 8.3.2

Choose the iterator according to what should happen to the input. With `.iter()`, the example keeps the original vector while collecting a new one; with `.into_iter()`, it moves the original values. If the goal is to change items in an existing vector through `.iter_mut()`, no new collection is needed. section 8.2

How Learn Rust in a Month of Lunches covers it

How deep it goes
Works through Vec and HashMap examples, type specification, and an unused-iterator warning; does not detail collect’s implementation.
Examples
Uses doubled numbers collected into a Vec, zipped number-word pairs collected into a HashMap, and a compiler warning for unused map.
What it assumes
Builds on vectors and basic iterator methods while explaining laziness and the role of collect.
What you can do after
Apply it via Rust iterator chains to build a Vec or HashMap from mapped or zipped items.
How it connects
Links collect to iterator laziness, map, zip, Vec, HashMap, and ownership through iter and into_iter.

Also explained in

Compare how 3 books explain collect →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.