liveBook · Manning

Map

As explained in Learn Rust in a Month of Lunches

A map is an associative data structure that stores key-value pairs and supports retrieving values by key.

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

How Learn Rust in a Month of Lunches covers it

How deep it goes
Defines creation, insertion, lookup, ordering, replacement, and entry-based counting and grouping.
Examples
Demonstrates city populations, city-to-country lookup, book counts, and grouping survey responses.
What you can do after
Apply Rust's HashMap to retrieve, replace, count, and group values by key.
How it connects
Connects HashMap to BTreeMap for ordered keys and Option for safe lookup results.

Also explained in

Compare how 42 books explain Map →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.