FromIterator

FromIterator lets you build a collection from an Iterator.

  1. fn main() {
  2.     let primes = vec![2, 3, 5, 7];
  3.     let prime_squares = primes.into_iter().map(|p| p * p).collect::<Vec<_>>();
  4.     println!("prime_squares: {prime_squares:?}");
  5. }

This slide should take about 5 minutes.

Iterator implements

  1. fn collect<B>(self) -> B
  2. where
  3. B: FromIterator<Self::Item>,
  4. Self: Sized

There are two ways to specify B for this method:

  • With the “turbofish”: some_iterator.collect::<COLLECTION_TYPE>(), as shown. The _ shorthand used here lets Rust infer the type of the Vec elements.
  • With type inference: let prime_squares: Vec<_> = some_iterator.collect(). Rewrite the example to use this form.

There are basic implementations of FromIterator for Vec, HashMap, etc. There are also more specialized implementations which let you do cool things like convert an Iterator<Item = Result<V, E>> into a Result<Vec<V>, E>.