Rust HashMap Key Value Retrieval & Printing
Rust Arrays: Exercise-4 with Solution
Write a Rust program that retrieves the value associated with a specific key from a HashMap and print it.
Sample Solution:
Rust Code:
use std::collections::HashMap; // Import the HashMap type from the standard library
fn main() {
// Create a HashMap to store key-value pairs
let mut my_map: HashMap<&str, i32> = HashMap::new(); // Key: &str (string slice), Value: i32
// Insert some key-value pairs into the HashMap
my_map.insert("a", 1);
my_map.insert("b", 2);
my_map.insert("c", 3);
// Define the key for which to retrieve the value
let key_to_retrieve = "b";
// Retrieve the value associated with the key from the HashMap
let value = my_map.get(key_to_retrieve); // Get the value associated with the key
// Print the value associated with the key, if it exists
match value {
Some(&v) => println!("Value associated with key '{}': {}", key_to_retrieve, v), // If the value exists, print it
None => println!("Key '{}' does not exist in the HashMap.", key_to_retrieve), // If the value does not exist, print a message
}
}
Output:
Value associated with key 'b': 2
Explanation:
Here is a brief explanation of the above Rust code:
- use std::collections::HashMap;: Imports the "HashMap" type from the standard library, allowing us to use HashMaps in our code.
- fn main() { ... }: Defines the main function, which is the entry point of the Rust program.
- let mut my_map: HashMap<&str, i32> = HashMap::new();: Creates an empty HashMap named 'my_map' with keys of type '&str' (string slice) and values of type "i32".
- my_map.insert("a", 1);: This line inserts a key-value pair into the "my_map" HashMap, where the key is the string slice "a" and the value is the integer 1. Similar lines insert additional key-value pairs.
- let key_to_retrieve = "b";: This line defines the key for which we want to retrieve the associated value from the HashMap.
- let value = my_map.get(key_to_retrieve);: This line retrieves the value associated with the specified key from the HashMap using the "get()" method and stores it in the variable 'value'.
- match value { ... }: This line starts a 'match' statement to handle the result of retrieving the value:
- If the value exists (Some(&v)), it prints the value associated with the key along with the key itself.
- If the value does not exist ('None'), it prints a message indicating that the key does not exist in the HashMap
Rust Code Editor:
Previous: Rust HashMap Key existence Check & Message printing.
Next: Rust HashMap Key-Value Update & Printing.
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-4.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics