HashMap
- Rust course
- Intermediate
- Lesson 54/115
- 4 min
Learn HashMap<K, V> and storing key-value pairs.
HashMap
HashMap<K, V> is a table mapping keys to values, with lookups in O(1) on average. The key type must be Eq + Hash:
use std::collections::HashMap;
let mut stok = HashMap::new();
stok.insert("elma", 10);
stok.insert("armut", 4);
stok.insert("elma", 12); // overwrites
println!("{:?}", stok.get("elma")); // Some(12)
println!("{:?}", stok.get("kivi")); // NoneBecause a key might be missing, get returns Option<&V>. stok["elma"] can be written too, but it panics if the key is missing.
Ownership and removal
insert takes ownership of the key and value; String keys are moved into the map. remove gives the value back, contains_key checks presence:
let mut renk: HashMap<String, u8> = HashMap::new();
let ad = String::from("kırmızı");
renk.insert(ad, 1); // ad was moved
println!("{}", renk.contains_key("kırmızı")); // true: searchable with &str
println!("{:?}", renk.remove("kırmızı")); // Some(1)A map with String keys can be searched with &str, because String: Borrow<str>.
Practice Stock table
Insert ("elma", 10), ("armut", 4) and again ("elma", 12) into a HashMap. Print the results of get("elma"), get("kivi") and len() on one line.
Starter code
use std::collections::HashMap;
fn main() {
// buraya yaz
}Sample solution
use std::collections::HashMap;
fn main() {
let mut stok = HashMap::new();
stok.insert("elma", 10);
stok.insert("armut", 4);
stok.insert("elma", 12);
println!("{:?} {:?} {}", stok.get("elma"), stok.get("kivi"), stok.len());
}Expected output
Some(12) None 2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 In what order do keys come when iterating a HashMap with <code>for</code>?
- By value
- Undefined; it may differ on every run Correct answer
- In insertion order
- Alphabetically
Explanation: Rust uses a randomly seeded hash per process against attacks. If you need an order, use a BTreeMap or a sorted Vec.
2 Safe read
let n = stok.____("elma"); // Option<&i32>
let n = stok.get("elma"); // Option<&i32>
Explanation: get returns None if the key is missing.
3 Operation and result
| Term | Meaning |
|---|---|
insert("elma", 12) (existed) |
Some(old value) |
get("kivi") |
None |
stok["kivi"] |
Panic |
remove("armut") |
Some(4) |