📜  Rust – HashMaps(1)

📅  最后修改于: 2023-12-03 14:47:10.427000             🧑  作者: Mango

Rust - HashMaps

HashMaps are a useful data structure in programming that allow you to store key-value pairs. They provide fast lookup and insertion times, making them efficient for many purposes.

Creating a HashMap

To start using HashMaps in Rust, you need to add the std::collections module to your project.

use std::collections::HashMap;

Then, you can create a new HashMap and insert key-value pairs into it.

let mut map = HashMap::new();

map.insert("key1", "value1");
map.insert("key2", "value2");
Accessing Values

You can access values in a HashMap using the get method, which returns an Option type.

if let Some(value) = map.get("key1") {
    println!("Value of key1: {}", value);
}

Alternatively, you can use the get_mut method to access and modify values directly.

if let Some(value) = map.get_mut("key1") {
    *value = "new value1";
}
Removing Values

To remove a value from a HashMap, you can use the remove method.

map.remove("key2");
Iterating over Entries

You can iterate over the entries of a HashMap using a for loop and the iter method.

for (key, value) in &map {
    println!("Key: {}, Value: {}", key, value);
}
Checking for Key Existence

You can check if a key exists in a HashMap using the contains_key method.

if map.contains_key("key1") {
    println!("Key1 exists");
}
HashMap Size

To get the number of key-value pairs in a HashMap, you can use the len method.

println!("HashMap size: {}", map.len());
Conclusion

HashMaps are a powerful data structure in Rust that allow you to store and retrieve key-value pairs efficiently. They provide a flexible and efficient way to manage data in your applications.