Learn Go← Dashboard

Key-value tables with the comma-ok idiom.

Creating and Using Maps

A map is Go's built-in hash table: an unordered key→value lookup.

Declaring

ages := map[string]int{}                  // empty
ages := make(map[string]int)              // identical
ages := map[string]int{"ada": 36, "alan": 41}

The type is map[K]V. K must be a type you can compare with == — most built-in types work; slices and functions don't.

Read, write, delete

go playground
Loading...

The comma-ok idiom

A missing key returns the zero value — same as a key whose value happens to be zero. To tell them apart, use the two-value form:

go playground
Loading...

Iterating

for k, v := range ages { ... }
for k := range ages { ... }
for _, v := range ages { ... }

The order is deliberately randomized — even with the same input, iteration order varies across runs. If you need stable order, collect the keys first and sort them:

go playground
Loading...

Maps are reference types

Like slices, a map "value" is really a small header that points to the data. Passing a map to a function does not copy it.

func clear(m map[string]int) { for k := range m { delete(m, k) } }

That mutation is visible to the caller.

Nil maps: read OK, write panics

var m map[string]int   // nil map
fmt.Println(m["x"])    // 0 — reading a nil map is fine
m["x"] = 1             // PANIC: assignment to entry in nil map

Always initialize with make or a literal before writing.

Comparing maps

You cannot compare two maps with == (except against nil). Use a loop or maps.Equal from the standard library (Go 1.21+):

import "maps"
maps.Equal(a, b)
What does `m["missing"]` return when the key is not in the map?
What happens when you write to a nil map: `var m map[string]int; m["x"] = 1`?