Skip to content
Justice Tech School

Maps In Depth

Writing to a nil map panics, so create it with make. Iteration order is random, so sort the keys when output must be stable.

Example
package main

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

func main() {
	m := map[string][]int{"a": {1}}
	m["a"] = append(m["a"], 2)
	m["b"] = append(m["b"], 9)
	keys := slices.Sorted(maps.Keys(m))
	for _, k := range keys {
		fmt.Println(k, m[k])
	}
	var nilMap map[string]int
	fmt.Println(nilMap["x"], len(nilMap))
}

Result

a [1 2]
b [9]
0 0

Exercise

Create a map.

m := (map[string]int)

Quiz Test

What happens when you write to a nil map?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.