liveBook · Manning

Map

As explained in Code Like a Pro in Rust

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

Use Rust’s `HashMap` when values need to be retrieved by key rather than by position. It is the standard choice for most key-based lookups; use `Vec` for a sequence of values instead. section 4.4 section 4.9

Two requirements shape the implementation:

  • Keys must implement `Eq` and `Hash`. For a compound key, `#[derive(Hash, Eq, PartialEq, Debug)]` generates the needed implementations and adds useful debug output. `Eq` also requires `PartialEq`. section 4.4.2
  • The default Siphash-1-3 hasher is adequate for most cases, but may be a poor fit for very small or very large keys. A custom hasher must satisfy `BuildHasher`, `Hasher`, and `Default` requirements. section 4.4 section 4.4.1

`BuildHasher::build_hasher()` creates a hasher. The required `Hasher` methods are `write()`, which accepts a byte slice, and `finish()`, which returns a `u64` hash. Existing crates can supply these implementations instead of requiring a new hash function. section 4.4.1

Listing 4.9 Code listing for using HashMap with MetroHash
use metrohash::MetroBuildHasher;
use std::collections::HashMap;
 
let mut map = HashMap::<String, String,
 MetroBuildHasher>::default();                #1
map.insert("hello?".into(), "Hello!".into());   #2
 
println!("{:?}", map.get("hello?"));            #3

This listing constructs a `HashMap` with `MetroBuildHasher`, inserts a pair, and retrieves its value by key. section 4.4.1

Listing 4.10 Code listing for a compound key type
#[derive(Hash, Eq, PartialEq, Debug)]
struct CompoundKey {
   name: String,
   value: i32,
}

This compound key demonstrates deriving the traits needed to use a struct as a map key. section 4.4.2

Start with `HashMap` and its default hasher for key-based lookup. Change the hasher when the key characteristics justify it; choose another collection only when its behavior addresses a concrete need. section 4.4 section 4.3.3

How Code Like a Pro in Rust covers it

How deep it goes
Explains key trait bounds and required custom-hasher methods, while deferring detailed treatment of traits and `#[derive]`.
Examples
Demonstrates a `MetroBuildHasher` map with insertion and lookup, plus a compound key with derived traits.
What it assumes
Assumes basic Rust syntax; introduces the relevant trait requirements without requiring a detailed understanding of trait implementation.
What you can do after
Apply it via `HashMap` with a derived compound key or a crate-provided custom hasher.
How it connects
Connects `HashMap` to `Vec`, `BTreeMap`, `Hash`, `Eq`, `BuildHasher`, and `Hasher`.

Also explained in

Compare how 42 books explain Map →

Related concepts

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