liveBook · Manning

Map

As explained in Go in Action, Second Edition

A map is a Go associative data structure that associates keys with values.

A Go map stores values under keys chosen for the problem, rather than integer positions. In a grocery inventory, a fruit name can lead directly to its average weight; separate, position-matched lists of names and weights are unnecessary. A map has one key type and one value type, written map[K]E. section 4.3 section 4.3.1

Look up shipping weights

fruitWeight := map[string]int{"orange": 130, "apple": 195} weight := 10*fruitWeight["apple"] + 30*fruitWeight["orange"] // 5850 The literal creates and populates the map. Assigning fruitWeight["apple"] = 200 would replace the existing value. section 4.3 section 4.3.2

A few behaviors matter when putting maps to work:

  • Initialize before assigning. make(map[string]int) and map[string]int{} create usable empty maps; assigning into a nil map declared with var panics. section 4.3.1
  • A missing key returns the value type’s zero value. Use value, found := m[key] when zero could also be a stored value and that distinction matters. section 4.3.2
  • Use range for keys and optional values, but never rely on iteration order. A range loop can also filter entries with delete when the map is not accessed elsewhere at the same time. section 4.3.5
  • Changes to a map’s contents inside a function are visible to its caller. section 4.3.6

Maps use hash tables internally: a hash function selects a bucket for a key, making distribution relevant to lookup as the map grows. For domain models, a named map type can express intent—for example, GroceryList maps ingredients to measurements, while a function combines measurements across recipes. section 4.3 section 5.2.2

How Go in Action, Second Edition covers it

How deep it goes
Explains declaration, lookup, mutation, iteration, and function sharing, with a bucket-level hash-table sketch rather than a detailed implementation.
Examples
Calculates fruit shipping weights, checks membership through Boolean values, filters ages, and aggregates recipe ingredients into a grocery list.
What it assumes
Builds on arrays, slices, primitive types, and structs while defining map syntax and keyed access directly.
What you can do after
Build it from scratch: initialize and use keyed collections, distinguish absent keys from stored zero values, and avoid relying on iteration order.
How it connects
Connects maps to arrays, slices, hash tables, zero values, named types, and structs.

Also explained in

Compare how 42 books explain Map →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Action, Second Edition. The section links point to the parts of the book it draws on.