Skip to content

Latest commit

 

History

History
27 lines (18 loc) · 1.11 KB

how-to-create-a-new-rust-hashmap-with-values.md

File metadata and controls

27 lines (18 loc) · 1.11 KB

How to create a new Rust HashMap with values?

// plain

Creating a new Rust HashMap with values is easy. You can use the collect() method to create a HashMap from a vector of key-value pairs.

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

This code creates a HashMap with the keys "a", "b", and "c" and the corresponding values 1, 2, and 3.

The code consists of the following parts:

  1. let mut map =: This declares a mutable variable map to store the HashMap.
  2. vec![("a", 1), ("b", 2), ("c", 3)]: This creates a vector of key-value pairs.
  3. .into_iter(): This converts the vector into an iterator.
  4. .collect::<HashMap<_, _>>(): This collects the iterator into a HashMap.

Helpful links

group: rust-hashmap

onelinerhub: How to create a new Rust HashMap with values?