A map stores key–value pairs: give it a key to find its matching value. In Rust, HashMap::new() creates a map, and insert(key, value) adds an entry. section 6.1.1
A few behaviors make maps easier to use safely:
- HashMap keys have no guaranteed order. Use BTreeMap when you need keys in order. section 6.1.1
- Square-bracket lookup can panic when a key is missing. get() instead returns Some(value) for a match or None when the key is absent. section 6.1.1
- Inserting a key that already exists replaces its value. The entry API can instead insert a default only when needed, making it useful for counting or grouping. section 6.1.1
use std::collections::HashMap;
fn main() {
let book_collection = vec![
"L'Allemagne Moderne",
"Le Petit Prince",
"Eye of the World",
"Eye of the World",
];
let mut book_hashmap = HashMap::new();
for book in book_collection {
let return_value = book_hashmap.entry(book).or_insert(0); #1
*return_value += 1; #2
}
for (book, number) in book_hashmap {
println!("{book}, {number}");
}
}
This example counts how often each book appears: entry(book).or_insert(0) supplies a starting count, then the count is increased. section 6.1.1









































