A map stores key–value pairs so a key can identify a value without being an integer index. The same idea is also called a dictionary or associative array. Rust provides two implementations: HashMap and BTreeMap. section 7.7.7
Countries and capitals
Treat a country name as a key and its capital as a value. A HashMap can store pairs such as "Tonga" → "Nuku'alofa"; after inserting them, `capitals["Tonga"]` retrieves the capital. section 7.7.8
Listing 7.18 An example of the basic operations of HashMap
1 use std::collections::HashMap;
2
3 fn main() {
4 let mut capitals = HashMap::new(); #1
5
6 capitals.insert("Cook Islands", "Avarua");
7 capitals.insert("Fiji", "Suva");
8 capitals.insert("Kiribati", "South Tarawa");
9 capitals.insert("Niue", "Alofi");
10 capitals.insert("Tonga", "Nuku'alofa");
11 capitals.insert("Tuvalu", "Funafuti");
12
13 let tongan_capital = capitals["Tonga"]; #2
14
15 println!("Capital of Tonga is: {}", tongan_capital);
16 }
Follow the complete Rust example from creating a HashMap through inserting capitals and retrieving one value. section 7.7.8
Choose the lookup method with missing keys in mind. Square-bracket access returns a read-only reference but panics if the key is absent. `.get()` returns `Option<&V>`, allowing the program to handle a missing value. HashMap also supports removal and iteration over keys, values, or pairs. section 7.7.9
A HashMap uses a hash function to turn a key into a fixed-width integer for an internal lookup table. Lookup is generally constant-time, though pathological hashing cases can hurt performance. Start with HashMap unless you need the key ordering, ordered iteration, or range queries offered by BTreeMap. section 7.7.7 section 7.7.10
Listing 7.20 Demonstrating range queries and ordered iteration of BTreeMap
1 use std::collections::BTreeMap;
2
3 fn main() {
4 let mut voc = BTreeMap::new();
5
6 voc.insert(3_697_915, "Amsterdam");
7 voc.insert(1_300_405, "Middelburg");
8 voc.insert( 540_000, "Enkhuizen");
9 voc.insert( 469_400, "Delft");
10 voc.insert( 266_868, "Hoorn");
11 voc.insert( 173_000, "Rotterdam");
12
13 for (guilders, kamer) in &voc {
14 println!("{} invested {}", kamer, guilders); #1
15 }
16
17 print!("smaller chambers: ");
18 for (_guilders, kamer) in voc.range(0..500_000) { #2
19 print!("{} ", kamer); #1
20 }
21 println!("");
22 }
Compare the choice with a BTreeMap whose numeric keys appear in order and whose range query selects smaller investments. section 7.7.10









































