A name-value pair associates one key with its corresponding value. A collection of these pairs is an abstract data structure used to look up values by non-integer or otherwise meaningful keys. Different programming communities call it a hash table, hash, table, dictionary, map, associative array, object, or key-value collection. section 7.7.7
Rust provides two implementations of this abstraction: HashMap and BTreeMap. HashMap uses a hash function to map variable-length keys to fixed-size integers and normally provides constant-time lookup. BTreeMap is useful when keys have a natural order and the program needs ordered iteration or range queries. section 7.7.7 section 7.7.10
Choose an implementation according to how the keys will be used:
- Use HashMap when efficient general lookup is the priority. section 7.7.7
- Use BTreeMap when keys have an inherent ordering, ordered iteration matters, or range queries are required. section 7.7.10
- In file storage, serialize each pair with a header containing a checksum, key length, and value length, then read and verify the record. section 7.7.2
Ordered investment records
A BTreeMap can associate investment amounts with trading chambers. Iterating over the map prints entries in key order, while range(0..500_000) selects chambers whose investments are below 500,000. 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 }
Shows a complete BTreeMap program that inserts key-value pairs, performs ordered iteration, and runs a range query. section 7.7.10










