liveBook · Manning

Collect

As explained in Idiomatic Rust

collect is an iterator method that consumes an iterator and builds a collection from its yielded items.

collect() consumes an iterator and builds a collection, usually a Vec. It also forces lazy iterator operations, such as map(), to run. Specify the target type when the compiler cannot infer it. section 3.2.5

let arr = [1, 2, 3, 4];
println!("{:?}", arr);
let vec: Vec<_> = arr.iter().map(|v| v.to_string()).collect();
println!("{:?}", vec);

Map an array’s values to strings, then collect them into a Vec. section 3.2.5

Choose a different collection

collect() can build a LinkedList too. Here, flat_map() turns each parse result into an iterator before collecting; failed parses are discarded, so use an approach that preserves errors when they matter. section 3.2.5

How Idiomatic Rust covers it

How deep it goes
Explains type annotation, lazy evaluation, and collection examples, but does not detail collect’s implementation.
Examples
Demonstrates collecting mapped strings into a Vec and parsed values into a LinkedList.
What you can do after
Apply it via Rust iterators to evaluate transformations and build a chosen collection.
How it connects
Connects collect to iterators, map, flat_map, Result, and standard-library collections.

Also explained in

Compare how 3 books explain collect →

Related concepts

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