Rust Tutorial: Convert Vector of Tuples to HashMap
Rust Arrays: Exercise-10 with Solution
Write a Rust program to convert a vector of tuples into a HashMap where the first element of each tuple is the key and the second element is the value.
Sample Solution:
Rust Code:
use std::collections::HashMap; // Import the HashMap type from the standard library
fn main() {
// Define a vector of tuples
let vec_of_tuples = vec![
("apple", 3),
("banana", 5),
("orange", 2),
];
// Create an empty HashMap
let mut hashmap_from_tuples: HashMap<&str, i32> = HashMap::new(); // Key: &str, Value: i32
// Iterate over the vector of tuples
for (key, value) in vec_of_tuples {
// Insert each tuple into the HashMap
hashmap_from_tuples.insert(key, value);
}
// Print the HashMap containing keys and values from the vector of tuples
println!("HashMap from tuples: {:?}", hashmap_from_tuples);
}
Output:
HashMap from tuples: {"orange": 2, "apple": 3, "banana": 5}
Explanation:
Here is a brief explanation of the above Rust code:
- use std::collections::HashMap;: This line imports the "HashMap" type from the standard library, allowing us to use HashMaps in our code.
- fn main() { ... }: This line defines the main function, which is the entry point of the Rust program.
- let vec_of_tuples = vec![ ... ];: This line defines a vector of tuples containing key-value pairs.
- let mut hashmap_from_tuples: HashMap<&str, i32> = HashMap::new();: This line creates an empty HashMap named 'hashmap_from_tuples' where the keys are string slices (&str) and the values are integers (i32).
- for (key, value) in vec_of_tuples { ... }: This line starts a loop to iterate over each tuple in the 'vec_of_tuples', extracting the key and value from each tuple.
- hashmap_from_tuples.insert(key, value);: This line inserts each tuple into the hashmap_from_tuples HashMap, where the first element of the tuple ('key') becomes the key in the HashMap and the second element of the tuple ('value') becomes the corresponding value in the HashMap.
- println!("HashMap from tuples: {:?}", hashmap_from_tuples);: This line prints the HashMap containing keys and values extracted from the vector of tuples after processing all the tuples.
Rust Code Editor:
Previous: Rust HashMap Tutorial: String Keys, Integer Vectors.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/rust/collections_and_data_structures/rust-hashmaps-exercise-10.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics