SyntaxPilot
Courses/Go Programming/Lesson 15

Go Programming · Lesson 15 of 89 · 11 min

Maps

map typemap literalsmake(map)insert and updatelookupcomma-ok idiomdeletelenrandomised iteration ordernil map write panicmaps of slices and structssets with map[T]struct{}clear (Go 1.21)maps package (Keys, Values, Clone, Equal)

These are the notes for Go episode 15. Slices keep things in order and you find them by position. Real life looks things up by name: what does a samosa cost? Did Ravi come today? Today you meet Go's built-in tool for that, the map. You will learn the map type, map literals, make(map), insert and update, lookup, the comma-ok idiom, delete, len, randomised iteration order, the nil map write panic, maps of slices and structs, sets with map[T]struct{}, clear (Go 1.21), and the maps package (Keys, Values, Clone, Equal). Every example runs as-is in the SyntaxPilot compiler (language: Go); outputs and errors are from real runs (Go 1.24).

The problem: two slices, one menu

With what we knew so far, Raju's menu is two parallel slices (two slices matched by position):

package main

import "fmt"

func main() {
    items := []string{"masala chai", "samosa", "bun maska", "cold coffee"}
    prices := []int{20, 15, 35, 60}

    want := "samosa"
    for i := 0; i < len(items); i++ {
        if items[i] == want {
            fmt.Println(want, "costs", prices[i])
        }
    }

    items = append(items, "vada pav")
    fmt.Println(len(items), len(prices))
}
samosa costs 15
5 4

Two problems: every question needs a search through all items (200 items, up to 200 checks), and the slices drift apart (5 items, 4 prices) with no warning. We want one structure where the name takes us straight to the price.

Your first map

Think of your phone's contact list:

Phone contacts In Go Name
A name: Mummy, Ravi, Office "samosa" the key: what you look up by; unique
Their number 15 the value: stored with its key
Name + number "samosa": 15 an entry (a key-value pair)
The whole list map[string]int a map from string keys to int values
  • A map stores entries and finds a value by its key without searching one by one. Other languages call it a dictionary or hash map.
  • Its type is map[KeyType]ValueType.
  • A map literal: map[string]int{"samosa": 15, ...}.
  • Lookup: m[key]. Insert a new key or update an existing one: m[key] = value. len(m) counts entries.
package main

import "fmt"

func main() {
    menu := map[string]int{
        "masala chai": 20,
        "samosa":      15,
        "bun maska":   35,
    }
    fmt.Println(menu["samosa"])

    menu["vada pav"] = 25
    menu["samosa"] = 18
    fmt.Println(menu, len(menu))
}
15
map[bun maska:35 masala chai:20 samosa:18 vada pav:25] 4

In a multi-line literal every entry, including the last, ends with a comma.

Missing keys and the comma-ok idiom

package main

import "fmt"

func main() {
    menu := map[string]int{"masala chai": 20, "water": 0}
    fmt.Println(menu["water"])
    fmt.Println(menu["pizza"])

    price, ok := menu["pizza"]
    fmt.Println(price, ok)

    if p, ok := menu["water"]; ok {
        fmt.Println("water is on the menu, Rs", p)
    }
}
0
0
0 false
water is on the menu, Rs 0
  • Looking up a missing key doesn't crash: it returns the zero value of the value type (0 here). So "free" and "missing" look the same.
  • The comma-ok idiom: v, ok := m[k]. ok is a bool, true only if the key exists.
  • The usual form puts it in an if with an init statement (episode 7): if v, ok := m[k]; ok { ... }.

delete

package main

import "fmt"

func main() {
    menu := map[string]int{"masala chai": 20, "samosa": 15, "bun maska": 35}
    delete(menu, "samosa")
    delete(menu, "pizza")
    fmt.Println(menu, len(menu))
}
map[bun maska:35 masala chai:20] 2

The built-in delete(m, key) removes an entry. Deleting a key that isn't there does nothing: no error, always safe.

Which types can be keys

package main

import "fmt"

func main() {
    seats := map[[]int]string{}
    fmt.Println(seats)
}
# command-line-arguments
./main.go:6:18: invalid map key type []int

To find a key, a map must be able to check whether two keys are equal with ==. A type whose values can be compared with == is comparable, and only comparable types can be keys. Slices, maps and functions are not comparable. Arrays are (episode 12), so a row-and-seat pair works as an array key:

package main

import "fmt"

func main() {
    seats := map[[2]int]string{}
    seats[[2]int{1, 2}] = "Asha"
    seats[[2]int{3, 4}] = "Ravi"
    fmt.Println(seats[[2]int{1, 2}], len(seats))
}
Asha 2

Strings, numbers, bools, arrays of comparable types, pointers (and structs of comparable fields, episode 19) can all be keys. Episode 16 explains why.

Iteration order is not guaranteed

for k, v := range m visits every entry:

package main

import "fmt"

func main() {
    menu := map[string]int{"chai": 20, "samosa": 15, "bun": 35,
        "vada": 25, "lassi": 40, "poha": 30}
    for item, price := range menu {
        fmt.Print(item, "=", price, " ")
    }
    fmt.Println()
}

Two real runs of the same program:

samosa=15 bun=35 vada=25 lassi=40 poha=30 chai=20 
chai=20 samosa=15 bun=35 vada=25 lassi=40 poha=30

The Go specification says "the iteration order over maps is not specified", and the runtime deliberately starts each iteration at a random position (the Go 1.24 source, internal/runtime/maps/table.go, says "Randomize iteration order by starting iteration at a random slot"). Never write code that depends on map order.

When you need a stable order, sort the keys:

package main

import (
    "fmt"
    "maps"
    "slices"
)

func main() {
    menu := map[string]int{"chai": 20, "samosa": 15, "bun": 35,
        "vada": 25, "lassi": 40, "poha": 30}
    keys := slices.Sorted(maps.Keys(menu))
    for _, item := range keys {
        fmt.Print(item, "=", menu[item], " ")
    }
    fmt.Println()
}
bun=35 chai=20 lassi=40 poha=30 samosa=15 vada=25 
  • maps.Keys(m) returns an iterator: a value that hands out the keys one at a time, which you can range over (since Go 1.23; full details in episode 32).
  • slices.Sorted(it) collects an iterator's values into a new sorted slice.

Note: fmt.Println(m) prints maps in key-sorted order to make output readable (the fmt package sorts them), but range never promises any order.

nil maps and make

package main

import "fmt"

func main() {
    var stock map[string]int
    fmt.Println(stock == nil, len(stock), stock["chai"])
    stock["chai"] = 50
}
true 0 0
panic: assignment to entry in nil map

goroutine 1 [running]:
main.main()
    /tmp/.../main.go:8 +0xc5
exit status 2
  • The zero value of a map is nil: reading works (length 0, missing keys give zero values), but writing panics.
  • Unlike a nil slice (append makes room), a map must be created before you write: make(map[K]V) or an empty literal map[K]V{}.
  • Real-life picture: a contact list app that was never installed. You can look and find nobody, but you can't save anyone.
package main

import "fmt"

func main() {
    stock := make(map[string]int)
    stock["chai"] = 50
    stock["chai"] += 10
    stock["milk"]++
    fmt.Println(stock)
}
map[chai:60 milk:1]

stock["milk"]++ on a missing key reads 0 and stores 1: the heart of every counter.

Maps of slices and maps of structs

A value can be any type:

package main

import "fmt"

func main() {
    tables := map[int][]string{}
    tables[4] = append(tables[4], "chai")
    tables[4] = append(tables[4], "samosa")
    tables[7] = append(tables[7], "lassi")
    fmt.Println(tables)

    type item struct {
        price int
        veg   bool
    }
    menu := map[string]item{"samosa": {15, true}, "omelette": {30, false}}
    fmt.Println(menu["omelette"].veg, menu)
}
map[4:[chai samosa] 7:[lassi]]
false map[omelette:{30 false} samosa:{15 true}]
  • Map of slices: a missing key gives a nil slice, and append accepts nil, so m[k] = append(m[k], v) works with no setup. This is the standard grouping pattern.
  • A struct groups a few named values, called fields, into one value: item has a price and a veg flag. menu["omelette"].veg reads a field. Structs get their own episode (19).
  • One limit to know: you can't take the address of a map entry (&menu["chai"] → invalid operation: cannot take address of menu["chai"] (map index expression of type int)), so to change one field of a struct value, read it, change it, and store it back.

Sets with map[T]struct{}

A set is a collection of unique things with no order, like a guard's guest register: each name once, even if they came twice. Go has no set type, but map keys are already unique.

  • We need no value, only the key. The empty struct type struct{} holds nothing and takes zero bytes; its only value is written struct{}{}.
  • So map[string]struct{} is Go's usual set. Membership test: comma-ok.
package main

import "fmt"

func main() {
    visited := map[string]struct{}{}
    for _, name := range []string{"Asha", "Ravi", "Asha", "Meena", "Ravi"} {
        visited[name] = struct{}{}
    }
    fmt.Println(len(visited), "unique customers")

    _, came := visited["Ravi"]
    fmt.Println("Ravi came?", came)

    clear(visited)
    fmt.Println(len(visited), visited)
}
3 unique customers
Ravi came? true
0 map[]

clear(m) (a built-in since Go 1.21) deletes every entry. The map is empty but still usable, not nil.

The maps package

package main

import (
    "fmt"
    "maps"
    "slices"
)

func main() {
    today := map[string]int{"chai": 20, "samosa": 15}
    backup := maps.Clone(today)
    today["chai"] = 25

    fmt.Println(maps.Equal(today, backup))
    fmt.Println(slices.Sorted(maps.Keys(backup)))
    fmt.Println(slices.Sorted(maps.Values(backup)))
}
false
[chai samosa]
[15 20]
Function What it does
maps.Clone(m) an independent copy (since Go 1.21)
maps.Equal(a, b) same keys with equal values?
maps.Keys(m) iterator over the keys (since Go 1.23)
maps.Values(m) iterator over the values (since Go 1.23)

Why Clone? Assigning a map shares it, just like slices share a backing array:

package main

import "fmt"

func main() {
    today := map[string]int{"chai": 20}
    backup := today
    today["chai"] = 25
    fmt.Println(backup["chai"])
}
25

And == doesn't compare maps: invalid operation: a == b (map can only be compared to nil). Use maps.Equal.

Mini project: word count of customer feedback

package main

import (
    "fmt"
    "maps"
    "slices"
    "strings"
)

func main() {
    feedback := "good chai good samosa great chai chai too sweet"
    counts := map[string]int{}
    for _, w := range strings.Fields(feedback) {
        counts[w]++
    }
    for _, w := range slices.Sorted(maps.Keys(counts)) {
        fmt.Printf("%-7s %d\n", w, counts[w])
    }
}
chai    3
good    2
great   1
samosa  1
sweet   1
too     1
  • strings.Fields(s) splits a string into words at whitespace and returns a []string.
  • counts[w]++ is a complete counter: missing words start at 0.
  • Sorting the keys makes the output stable.

The next problem: a map finds a key almost instantly, with no loop we can see. How? Episode 16 opens the map up: hash functions, buckets, growth, and Go 1.24's Swiss Tables.

Common mistakes (and the real error messages)

You wrote Real error / what happens Fix
var m map[string]int; m["chai"] = 50 panic: assignment to entry in nil map m := make(map[string]int)
price := menu["pizza"] no error: 0 for a missing key price, ok := menu["pizza"]
relying on range order no error: order changes between runs slices.Sorted(maps.Keys(m))
backup := today then edit today no error: backup changes too backup := maps.Clone(today)
a == b on maps invalid operation: a == b (map can only be compared to nil) maps.Equal(a, b)
map[[]int]string{} invalid map key type []int keys must be comparable (episode 16)
&menu["chai"] invalid operation: cannot take address of menu["chai"] (map index expression of type int) read, change, store back

Practice

  1. A phone book: add three contacts, look one up with comma-ok, delete one.
  2. Find the most common word in a sentence (break ties alphabetically).
  3. Group names by first letter: map[byte][]string, printed in sorted order.
  4. Find the items two orders have in common using a set.
Solutions

1.

package main

import "fmt"

func main() {
    book := map[string]string{}
    book["Mummy"] = "98100 11111"
    book["Ravi"] = "98100 22222"
    book["Office"] = "011 2345 6789"

    if num, ok := book["Ravi"]; ok {
        fmt.Println("Ravi:", num)
    }
    delete(book, "Office")
    _, ok := book["Office"]
    fmt.Println("Office still saved?", ok, "contacts:", len(book))
}
Ravi: 98100 22222
Office still saved? false contacts: 2
  1. "chai" and "is" both appear 3 times; the tie-break keeps the answer the same on every run even though map order changes:
package main

import (
    "fmt"
    "strings"
)

func main() {
    text := "chai is hot chai is sweet and chai is cheap"
    counts := map[string]int{}
    for _, w := range strings.Fields(text) {
        counts[w]++
    }
    best, bestN := "", 0
    for w, n := range counts {
        if n > bestN || (n == bestN && w < best) {
            best, bestN = w, n
        }
    }
    fmt.Println(best, bestN)
}
chai 3
  1. n[0] is the first byte of the string (episode 17 explains bytes):
package main

import (
    "fmt"
    "maps"
    "slices"
)

func main() {
    names := []string{"Asha", "Ravi", "Arjun", "Meena", "Rohit", "Anil"}
    groups := map[byte][]string{}
    for _, n := range names {
        groups[n[0]] = append(groups[n[0]], n)
    }
    for _, k := range slices.Sorted(maps.Keys(groups)) {
        fmt.Println(string(k), groups[k])
    }
}
A [Asha Arjun Anil]
M [Meena]
R [Ravi Rohit]

4.

package main

import (
    "fmt"
    "slices"
)

func main() {
    asha := []string{"chai", "samosa", "bun maska"}
    ravi := []string{"vada pav", "chai", "bun maska", "lassi"}

    inAsha := map[string]struct{}{}
    for _, it := range asha {
        inAsha[it] = struct{}{}
    }
    var both []string
    for _, it := range ravi {
        if _, ok := inAsha[it]; ok {
            both = append(both, it)
        }
    }
    slices.Sort(both)
    fmt.Println(both)
}
[bun maska chai]

Quick quiz

What does this print?

func main() {
    m := map[string]int{"a": 1}
    m["b"]++
    v, ok := m["c"]
    fmt.Println(len(m), m["b"], v, ok)
}
  • A. 1 0 0 false
  • B. 2 1 0 false
  • C. 2 1 0 true
  • D. panic
Answer

B. 2 1 0 false. m["b"]++ reads 0 for the missing key and stores 1, so there are 2 entries. "c" is missing: 0, false. A comma-ok lookup never adds a key.

Interview questions

  • What is a map? What are its key and value types?
  • What does looking up a missing key return? How do you tell "missing" from "zero"?
  • Is delete on a missing key an error?
  • Why does iterating over a map give a different order each run? How do you get a stable order?
  • What happens when you write to a nil map? How is that different from appending to a nil slice?
  • How do you implement a set in Go? Why struct{}?
  • Does assigning a map copy it? How do you copy one?
  • Can you compare two maps with ==?

Glossary

Term Meaning Example
Map a collection of key → value entries, found by key map[string]int
Key what you look up by; unique in a map "samosa"
Value what is stored with a key 15
Entry one key-value pair "samosa": 15
Comparable a type whose values can be compared with ==; required for keys string, int, [2]int
Map literal a map written in code map[string]int{"chai": 20}
Dictionary / hash map other languages' names for a map Python dict
Parallel slices slices matched by position items[i], prices[i]
Lookup reading a value by key menu["samosa"]
Insert / update m[k] = v adds a new key or replaces a value menu["vada pav"] = 25
Zero value what a missing key returns 0, "", false, nil
Comma-ok idiom a second bool result saying whether the key exists v, ok := m[k]
Init statement a short statement before an if condition if v, ok := m[k]; ok
delete built-in that removes a key; safe if missing delete(menu, "samosa")
len number of entries len(menu)
Iteration order the order range visits entries: unspecified, varies two runs differ
Iterator a value that hands out items one at a time for range maps.Keys(m)
slices.Sorted collects an iterator into a sorted slice slices.Sorted(maps.Keys(m))
nil map a map's zero value: reads work, writes panic var stock map[string]int
make (map) creates a map ready for writing make(map[string]int)
Counter m[k]++ counting occurrences word count
Grouping m[k] = append(m[k], v) orders per table
Struct a value made of named fields item{price: 15, veg: true}
Field one named part of a struct .veg
Set unique items, no order map[string]struct{}
Empty struct struct{}: no fields, zero bytes struct{}{}
clear built-in (Go 1.21) that empties a map clear(visited)
maps.Clone an independent copy of a map backup := maps.Clone(today)
maps.Equal same keys and equal values? false
maps.Keys / maps.Values iterators over keys / values sorted with slices.Sorted
strings.Fields splits text into words at whitespace []string{"good", "chai"}

Summary

  • A map map[K]V finds a value by its key. m[k] = v inserts or updates, len(m) counts entries.
  • A missing key gives the zero value; use v, ok := m[k] to tell missing from zero.
  • delete(m, k) is always safe. clear(m) empties a map.
  • Iteration order is not specified and varies between runs: sort the keys with slices.Sorted(maps.Keys(m)).
  • A nil map can be read but panics on write: use make or a literal.
  • Keys must be comparable (no slice keys). Values can be slices (grouping) or structs. map[T]struct{} is a set.
  • Maps are shared on assignment: maps.Clone copies, maps.Equal compares.

Next episode: map internals: hash functions, buckets, load factor, growth, Swiss Tables (Go 1.24), comparable keys, NaN keys, and why maps aren't safe for concurrent use.