Skip to main content
eLearner.app
Module 4 · Lesson 3 of 518/50 in the course~12 min
Module lessons (3/5)

Maps: keys and values

A map is a key→value hash table: map[K]V. Maps are reference types: passed to a function, they share the same storage. They must be initialized before you can write to them (with make or a literal).

Creation

Go
// with a literal
prices := map[string]int{"pane": 2, "latte": 3}

// with make
counters := make(map[string]int)
counters["a"] = 1

// nil map (readable, NOT writable)
var m map[string]int
fmt.Println(m["x"])    // 0 — ok
// m["y"] = 1          // PANIC

Basic operations

Go
m := map[string]int{"a": 1}

m["b"] = 2              // insert/update
v := m["a"]             // get; if missing: zero value
delete(m, "a")          // remove (ok even if the key doesn't exist)
n := len(m)             // number of entries

Comma-ok: distinguishing "missing" from "zero value"

Go
v, ok := m["x"]
if !ok {
    fmt.Println("key missing")
} else {
    fmt.Println("found:", v)
}

It's the only way to know whether a key exists, because m["x"] returns the zero value even when the key isn't there. A fundamental pattern.

Iteration: randomized order

Go
for k, v := range m {
    fmt.Println(k, v)
}

Keys: only comparable types

Keys must be comparable: string, numbers, bool, pointers, channels, interfaces, arrays of comparable types, structs of comparable fields. Slices, maps and functions are not comparable → they cannot be keys.

Go
m := map[[2]int]string{}   // ok: array is comparable
// m := map[[]int]string{} // ERROR: slice is not comparable

Pattern: counters

One of the most common uses of maps:

Go
words := []string{"a", "b", "a", "c", "b", "a"}
freq := map[string]int{}
for _, w := range words {
    freq[w]++   // access to a missing key is 0 → 0+1 = 1
}
// freq = {"a": 3, "b": 2, "c": 1}

Try it

Exercise#go.m4.l3.e1
Attempts: 0Loading…

Create a map[string]int with values 'a' -> 1 and 'b' -> 2, then add 'c' -> 3.

Loading editor…
Show hint

Literal: `map[K]V{"key": value, ...}`.

Solution available after 3 attempts

Exercise#go.m4.l3.e2
Attempts: 0Loading…

Use the comma-ok pattern to read the key 'x' (not present) into v, ok and print both.

Loading editor…
Show hint

Two return values: the value and a presence boolean.

Solution available after 3 attempts

Quiz#go.m4.l3.e3
Ready

What happens when writing to a nil map?

Go
var m map[string]int
m["a"] = 1
Answer options

Recap

  • map[K]V: key-value, reference, hash-backed.
  • Initialize with make or a literal; nil map → panic on write.
  • v, ok := m[k] is the only way to distinguish "missing" from "zero value".
  • delete(m, k) removes; ok even if k doesn't exist.
  • range iteration: randomized order.
  • Keys: only comparable types (no slice/map/func).
  • Counters pattern: freq[k]++ leverages the implicit zero value.