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 remove an element from a Rust HashMap if a condition is met?
- How to use a custom hash function with a Rust HashMap?
- How to use an enum in a Rust HashMap?
- How to insert an element into a Rust HashMap if it does not already exist?
- How to create a HashMap of structs in Rust?
- How to create a new Rust HashMap with values?
- How to create a HashMap of HashMaps in Rust?
- How to create a HashMap of pointers in Rust?
- How to convert the keys of a Rust HashMap to a vector?
More of Rust
- How to create a HashMap of HashMaps in Rust?
- How to swap elements in a Rust slice?
- How to extend struct from another struct in Rust
- How to get a capture group using Rust regex?
- How to replace a capture group using Rust regex?
- Hashshet example in Rust
- How to get an entry from a HashSet in Rust?
- How to convert a Rust slice of u8 to a string?
- How to find the first match in a Rust regex?
- How to calculate the sum of a Rust slice?
See more codes...