A key identifies a value in a map. Think of an address list: “email” can be the key, and an email address can be its value. In Rust, a HashMap stores these key–value pairs. Add one with .insert(key, value), then use the key to find its value. section 6.1.1
use std::collections::HashMap;
fn main() {
let canadian_cities = vec!["Calgary", "Vancouver", "Gimli"];
let german_cities = vec!["Karlsruhe", "Bad Doberan", "Bielefeld"];
let mut city_hashmap = HashMap::new();
for city in canadian_cities {
city_hashmap.insert(city, "Canada");
}
for city in german_cities {
city_hashmap.insert(city, "Germany");
}
println!("{:?}", city_hashmap["Bielefeld"]);
println!("{:?}", city_hashmap.get("Bielefeld"));
println!("{:?}", city_hashmap.get("Bielefeldd"));
}
Here, city names are keys and countries are values. The example inserts each pair, then looks up “Bielefeld” in two ways. section 6.1.1
Square-bracket lookup returns the value, but it panics if the key is missing. Use .get() when you are unsure: it returns Some(value) for an existing key and None for a missing one. In the city example, “Bielefeld” exists; “Bielefeldd” does not. section 6.1.1
A key also determines what happens when you add another pair. Inserting a value under an existing key replaces the old value. If you want to keep the existing value, .entry(key).or_insert(default) inserts the default only when the key is absent. That pattern can also initialize a count before you increase it. section 6.1.1
Do not rely on a HashMap’s keys appearing in a particular order when you loop over it. If you need keys in order, use a BTreeMap; its methods are similar for these examples. section 6.1.1









