rustHow to create a Rust HashMap from a vector of tuples?
Creating a Rust HashMap from a vector of tuples is a simple process. The following example code creates a HashMap from a vector of tuples:
let mut map = HashMap::new();
let v = vec![(1, "a"), (2, "b"), (3, "c")];
for (key, value) in v {
map.insert(key, value);
}
The output of the example code is:
HashMap { 1: "a", 2: "b", 3: "c" }
Code explanation
let mut map = HashMap::new();- This creates a new, empty HashMap.let v = vec![(1, "a"), (2, "b"), (3, "c")];- This creates a vector of tuples.for (key, value) in v {- This starts a loop that iterates over each tuple in the vector.map.insert(key, value);- This inserts the key and value from the tuple into the HashMap.}- This ends the loop.
Helpful links
Related
- How to implement PartialEq for a Rust HashMap?
- How to compare two Rust HashMaps?
- How to print a Rust HashMap?
- How to sort a Rust HashMap?
- How to use a HashBrown with a Rust HashMap?
- How to use a Rust HashMap in a multithreaded environment?
- How to convert a Rust HashMap to a BTreeMap?
- How to create a Rust HashMap with a string key?
- How to build a Rust HashMap from an iterator?
- How to pop an element from a Rust HashMap?
More of Rust
- How to get a capture group using Rust regex?
- How to use regex to match a double quote in Rust?
- How to replace a capture group using Rust regex?
- How to match whitespace with a regex in Rust?
- How to match a URL with a regex in Rust?
- How to replace all matches using Rust regex?
- How to use non-capturing groups in Rust regex?
- How to replace strings using Rust regex?
- How to split a string with Rust regex?
- Regex example to match multiline string in Rust?
See more codes...