Rust HashMap: Inserting Name-Age pairs
Rust Arrays: Exercise-1 with Solution
Write a Rust program that creates an empty HashMap and inserts key-value pairs representing the names and ages of people.
Sample Solution:
Rust Code:
use std::collections::HashMap; // Import the HashMap type from the standard library
fn main() {
// Create an empty HashMap to store names and ages of people
let mut people: HashMap<String, u32> = HashMap::new(); // Key: String (name), Value: u32 (age)
// Insert key-value pairs representing names and ages of people into the HashMap
people.insert(String::from("Lennart"), 40);
people.insert(String::from("Nagendra"), 51);
people.insert(String::from("Adino"), 35);
// Print the HashMap containing names and ages of people
println!("People: {:?}", people);
}
Output:
People: {"Lennart": 40, "Nagendra": 51, "Adino": 35}
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's collections module, allowing the use of HashMaps in the code.
- fn main() { ... }: This line defines the main function, which serves as the entry point of the Rust program.
- let mut people: HashMap<String, u32> = HashMap::new();: This line declares a mutable variable named 'people' and initializes it as an empty HashMap. The HashMap is defined to have keys of type "String" (representing names) and values of type u32 (representing ages).
- people.insert(String::from("Lennart"), 40);: This line inserts a key-value pair into the people HashMap, where the key is the String "Lennart" (representing a person's name) and the value is the u32 40 (representing Lennart's age). Similar lines insert additional key-value pairs for other people's names and ages.
- println!("People: {:?}", people);: This line prints the content of the 'people' HashMap, including all the inserted names and ages, using debug formatting. The {:?} format specifier prints the HashMap, showing its internal structure
Rust Code Editor:
Previous: Rust Hashmaps Exercises.
Next: Rust HashMap Iteration: Printing Key-Value pairs.
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-1.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics