liveBook · Manning

Map

As explained in Learn Go with Pocket-Sized Projects

An associative array is a collection that associates keys with values rather than using only positional indexes.

When a growing list of language choices makes a switch unwieldy, put the choices in a map. A Go map is an unordered collection of distinct keys, each associated with one value. For a phrasebook, `map[language]string` associates each supported language code with its greeting. section 2.3 section 2.3.1

Listing 2.9 main.go: Using a map
package main

import (
    "fmt"
)

func main() {
    greeting := greet("en")
    fmt.Println(greeting)
}

// language represents the language's code
type language string

// phrasebook holds greeting for each supported language
var phrasebook = map[language]string{ #1
    "el": "Χαίρετε Κόσμε",     // Greek
    "en": "Hello world",       // English
    "fr": "Bonjour le monde",  // French
    "he": "שלום עולם",         // Hebrew
    "ur": "ہیلو دنیا",         // Urdu
    "vi": "Xin chào Thế Giới", // Vietnamese
}

// greet says hello to the world in various languages
func greet(l language) string {
    greeting, ok := phrasebook[l] #2
    if !ok {
        return fmt.Sprintf("unsupported language: %q", l)
    }

    return greeting
}

The complete phrasebook example shows a map literal, a lookup, and the unsupported-language path together. section 2.3.1

Read with `value, ok := m[key]`. `ok` reports whether the key exists; without it, a missing key looks like the value type’s zero value. For a string map, that is `""`, which might also be a stored value. Write with `m[key] = value`, and create an empty map for writing with `make(map[Key]Value)`. Keys must be comparable: a `Book` can be a key if its fields are comparable, but slices, maps, and functions cannot be keys. section 2.3.1 section 3.2.1

Count books on shelves

Start with `count := make(map[Book]uint)`. For each reader, loop over their books and run `count[book]++`. The map holds one counter per distinct book. To test a result, range over the expected map and check both `got[book]` and its `ok` value; matching counts alone would miss an absent key. section 3.2.1

Listing 3.12 bookworm.go: The booksCount() function
// booksCount registers all the books and their occurrences
// from the bookworms shelves.
func booksCount(bookworms []Bookworm) map[Book]uint {
    count := make(map[Book]uint) #1

    for _, bookworm := range bookworms { #2
        for _, book := range bookworm.Books {
            count[book]++ #3
        }
    }

    return count
}

The complete counting function shows nested slice loops feeding a map whose keys are books and whose values are occurrence counts. section 3.2.1

Maps also organize named test cases: `map[string]testCase` pairs a readable case name with its inputs and expectations, then `range` runs the cases. For membership without an associated payload, `map[Book]struct{}` can act as a set; a lookup’s `ok` value answers whether a book is present. section 3.1.4 section 3.4.2

A map can sit behind a reusable cache. `Cache[K comparable, V any]` stores `map[K]V`; its constructor initializes the map before writes, while methods expose reading, upserting, and deleting. Choose whether the map stores values or pointers deliberately: that choice changes the cache’s ownership and memory tradeoffs. section 7.1.3

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Works through literals, initialization, reads, writes, missing keys, comparable keys, iteration, and a map-backed cache; does not develop hash-table internals.
Examples
Uses a multilingual phrasebook, bookshelf occurrence counts, named JSON-loading test cases, and a generic cache.
What it assumes
Assumes familiarity with Go functions and types while introducing map syntax through concrete applications.
What you can do after
Build it from scratch: create maps for lookup, counting, or membership, and check key presence when absence matters.
How it connects
Connects maps to switch statements, slices, table-driven tests, sets, and generic caches.

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 Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.