rustHow to create a new Rust HashMap with values?
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:
let mut map =: This declares a mutable variablemapto store the HashMap.vec![("a", 1), ("b", 2), ("c", 3)]: This creates a vector of key-value pairs..into_iter(): This converts the vector into an iterator..collect::<HashMap<_, _>>(): This collects the iterator into a HashMap.
Helpful links
Related
- How to sort the keys in a Rust HashMap?
- How to use a custom hash function with a Rust HashMap?
- How to build a Rust HashMap from an iterator?
- How to clear a Rust HashMap?
- How to check if a Rust HashMap contains a key?
- How to create a Rust HashMap?
- How to remove an element from a Rust HashMap if a condition is met?
- How to print a Rust HashMap?
- How to print the keys of a Rust HashMap?
- How to create a Rust HashMap with a string key?
More of Rust
- How to replace strings using Rust regex?
- How to match whitespace with a regex in Rust?
- Yield example in Rust
- How do I print a variable in Rust?
- How to use regex lookbehind in Rust?
- Bitwise operator example in Rust
- How to use captures_iter with regex in Rust?
- How to use regex to match a double quote in Rust?
- How to perform matrix operations in Rust?
- How to sort a Rust HashMap?
See more codes...