Go core
Browse topics

Creating, updating and listing maps

Version
1.27
Review
Draft

Summary#

A map associates keys with values. Assign to add or replace an entry and use delete to remove one. Iteration order is unspecified, so sort the keys when order matters.

Syntax#

go
counts := map[string]int{}
counts[key] = value
delete(counts, key)
keys := slices.Sorted(maps.Keys(counts))
backup := maps.Clone(counts)

Example#

go
package main

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

func main() {
	stock := map[string]int{"pear": 3, "apple": 5}
	stock["fig"] = 2
	stock["pear"] += 4
	delete(stock, "apple")
	delete(stock, "mango") // missing keys are fine
	fmt.Println(len(stock))

	for _, name := range slices.Sorted(maps.Keys(stock)) {
		fmt.Println(name, stock[name])
	}

	backup := maps.Clone(stock)
	stock["fig"] = 100
	fmt.Println(backup["fig"], stock["fig"])

	var tags map[string][]string // nil: readable, not writable
	fmt.Println(len(tags["fruit"]))
	tags = make(map[string][]string)
	tags["fruit"] = append(tags["fruit"], "fresh")
	fmt.Println(tags)
}

Expected output#

Text
2
fig 2
pear 7
2 100
0
map[fruit:[fresh]]

Common mistakes#

Writing to a nil map panics, so initialize it with make or a literal. A map lookup does not give you an addressable struct value. To update one of its fields, copy the struct out, change it and store it again, or store pointers. maps.Clone is shallow. Pointer, slice or map values can still share data with the original.

Version applicability#

Map assignment and delete work from Go 1.0. maps.Clone arrived with the maps package in Go 1.21. The example uses maps.Keys and slices.Sorted, which require Go 1.23 or later.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0