Learn Map in Go

map[string]int{"Tendon Meatballs": 15} stores pairs of a key and a value. m[k] reads, m[k] = v adds or replaces, delete(m, k) deletes, len(m) counts the…

A customer asks "How much is the Iced Tea?" Bimo doesn't read the price list on the wall from the top line down. He looks straight at the Iced Tea line: 5,000.

That is how a map works: you give it the key, and the map hands you the value straight away, without walking through its items one by one. The dish name is the key, the price is the value. In JavaScript this is like an object. The difference is that in Go every key has one type, and so does every value.

Making a map

prices := map[string]int{
	"Tendon Meatballs": 15,
	"Chicken Noodles":  12,
	"Iced Tea":         5,
}
fmt.Println(prices)                     // map[Chicken Noodles:12 Iced Tea:5 Tendon Meatballs:15]
fmt.Println(prices["Tendon Meatballs"]) // 15
fmt.Println(len(prices))                // 3

Add, change, delete

prices["Iced Orange"] = 6         // a new key: added
prices["Iced Tea"] = 4            // a key that exists: its value is replaced
delete(prices, "Chicken Noodles") // deleted
delete(prices, "Chicken Soup")    // the key isn't there: nothing happens
fmt.Println(prices, len(prices))
map[Iced Orange:6 Iced Tea:4 Tendon Meatballs:15] 3

Adding and changing are written exactly the same way. A key appears only once in a map, so writing to a key that already exists replaces it.

A key that isn't there: the zero value and comma-ok

Chicken Soup isn't on the price list. Before you look at the code, guess: does prices["Chicken Soup"] give an error, nil or 0?

fmt.Println(prices["Chicken Soup"]) // 0

price, found := prices["Chicken Soup"]
fmt.Println(price, found)           // 0 false

price, found = prices["Tendon Meatballs"]
fmt.Println(price, found)           // 15 true

range over a map: the order isn't fixed

for name, price := range prices {
	fmt.Println(name, price)
}

Run it twice and the order can differ:

Tendon Meatballs 15
Iced Tea 4
Iced Orange 6
Iced Tea 4
Iced Orange 6
Tendon Meatballs 15

Go deliberately doesn't promise any order for range over a map, so don't rely on it. Need a fixed order? Sort the keys first: for _, name := range slices.Sorted(maps.Keys(prices)) (Go 1.23 and newer, with import "maps" and "slices").

Counting with a map

Because a key that isn't there yet reads as 0, counts[p]++ works for counting straight away, without filling anything in first:

orders := []string{"Tendon Meatballs", "Iced Tea", "Tendon Meatballs", "Chicken Noodles", "Tendon Meatballs", "Iced Tea"}
counts := make(map[string]int)
for _, p := range orders {
	counts[p]++
}
fmt.Println(counts)      // map[Chicken Noodles:1 Iced Tea:2 Tendon Meatballs:3]
fmt.Println(len(counts)) // 3
p counts[p] before after
Tendon Meatballs 0 1
Iced Tea 0 1
Tendon Meatballs 1 2
Chicken Noodles 0 1
Tendon Meatballs 2 3
Iced Tea 1 2

Text separated by spaces can be counted the same way: split it into a slice first with strings.Split(text, " "), then range over the result. Don't forget import "strings"; without it Go refuses with undefined: strings. len(counts) gives the number of different keys.

A nil map: you can read it, not write it

var prices map[string]int               // not made yet: nil
fmt.Println(prices["Tendon Meatballs"]) // 0, reading is safe
prices["Tendon Meatballs"] = 15         // panic
0
panic: assignment to entry in nil map

goroutine 1 [running]:
main.main()
	/app/main.go:8 +0x85
exit status 2

📌 Maps and goroutines

A built-in map isn't safe to write from several goroutines at once: Go stops the program with fatal error: concurrent map writes. How to make it safe comes in the Mutex & Sync lesson.

⚠️ Why does the map panic, or why is the number 0?

TL;DR: map[string]int{"Tendon Meatballs": 15} stores pairs of a key and a value. m[k] reads, m[k] = v adds or replaces, delete(m, k) deletes, len(m) counts the pairs. A key that isn't there reads as the zero value (0), and v, ok := m[k] gives ok = false to tell them apart. The order of range isn't fixed, while fmt.Println prints the keys sorted. A nil map (var m map[string]int) can be read but panics when written, so make it first with make(map[string]int) or map[string]int{}. m[k]++ is the short way to count occurrences.

⚡ Keys and values

Write:

prices := map[string]int{
	"Tendon Meatballs": 15,
	"Chicken Noodles":  12,
	"Iced Tea":         5,
}
fmt.Println(prices["Tendon Meatballs"]) // 15

Meaning: Give it the key, and the map hands you the value straight away. prices[k] = v adds or replaces, delete(prices, k) deletes.

⚡ A key that isn't there

Guess first: Chicken Soup isn't on the price list. Does prices["Chicken Soup"] give an error, nil or 0?

0, the zero value of the value type. To tell it apart from a price that really is 0, take two values: price, found := prices["Chicken Soup"] gives 0 false.

Meaning: This pattern is called comma-ok, and its second variable is often named ok.

⚡ Make it first, then fill it

Guess first: var prices map[string]int, then prices["Tendon Meatballs"] = 15. What happens?

A panic: assignment to entry in nil map. The map hasn't been made yet, so it's still nil. Reading it is safe, writing it is not.

Meaning: A map that is ready to fill is made with make(map[string]int) or the literal map[string]int{}.

What you will learn