how to make map in rust language
To create a map in the Rust programming language, you can use the HashMap
data structure provided by the standard library. Here's an example of how you can create and use a map in Rust:
use std::collections::HashMap;
fn main() {
// Create a new HashMap
let mut map: HashMap<String, i32> = HashMap::new();
// Insert key-value pairs into the map
map.insert(String::from("apple"), 3);
map.insert(String::from("banana"), 2);
map.insert(String::from("orange"), 5);
// Access values in the map
if let Some(quantity) = map.get("apple") {
println!("The quantity of apples is: {}", quantity);
}
// Update values in the map
if let Some(quantity) = map.get_mut("banana") {
*quantity += 1;
}
// Remove a key-value pair from the map
map.remove("orange");
// Iterate over the map
for (key, value) in &map {
println!("Key: {}, Value: {}", key, value);
}
}
This code snippet demonstrates how to create a HashMap
called map
that maps String
keys to i32
values. It inserts key-value pairs into the map, accesses and updates values, removes a key-value pair, and iterates over the map to print its contents.