Storing Keys with Associated Values in Hash Maps
In this chapter, we'll explore store key-value pairs with hash maps.
Storing Keys with Associated Values in Hash Maps
The HashMap<K, V> type stores a mapping of keys of type K to values of type V using a hashing function to determine how to place these key-value pairs into memory.
Creating a Hash Map
use std::collections::HashMap
let mut scores = HashMap::new()
scores.insert("Blue", 10)
scores.insert("Yellow", 50)Accessing Values
Use get to retrieve values:
let team_name = "Blue"
let score = scores.get(team_name) // Returns Option<int>
match score {
Some(s) => println(team_name, ": ", s)
None => println("Team not found")
}Iterating Over Hash Maps
for (key, value) in scores {
println(key, ": ", value)
}Updating Values
Overwrite existing value:
scores.insert("Blue", 25) // Replaces 10 with 25Insert only if key doesn't exist:
scores.entry("Blue").or_insert(50) // Won't change (Blue exists)
scores.entry("Red").or_insert(50) // Inserts Red: 50Update based on old value:
let text = "hello world wonderful world"
let mut map = HashMap::new()
for word in text.split(" ") {
let count = map.entry(word).or_insert(0)
*count = *count + 1
}
// {"hello": 1, "world": 2, "wonderful": 1}Hash Map Methods
let mut map = HashMap::new()
map.insert("a", 1)
map.len() // Number of entries
map.is_empty() // Check if empty
map.contains_key("a") // Check if key exists
map.remove("a") // Remove and return value
map.clear() // Remove all entriesSummary
Vectors, strings, and hash maps provide essential ways to store collections of data. Combined with ownership and borrowing rules, they help you write safe and efficient code.
Next, let's learn about Error Handling in Chapter 9.