9951 explained code solutions for 126 technologies


rustHow to build a Rust HashMap from an iterator?


To build a Rust HashMap from an iterator, you can use the collect() method. This method takes an iterator and collects its elements into a collection. For example, the following code creates a HashMap from an iterator of tuples:

let map: HashMap<_, _> = [(1, "a"), (2, "b"), (3, "c")].iter().collect();

The output of this code is:

{1: "a", 2: "b", 3: "c"}

The code consists of the following parts:

  • let map: HashMap<_, _>: This declares a variable map of type HashMap with generic type parameters _ and _.
  • [(1, "a"), (2, "b"), (3, "c")]: This is an array literal containing tuples of integers and strings.
  • .iter(): This converts the array into an iterator.
  • .collect(): This collects the elements of the iterator into a collection.

Helpful links

Edit this code on GitHub