Go Maps Explained with Simple Examples

Updated 4 min read
Go Maps featured image: cards showing a map type, the comma ok check and delete

Go maps store values by name instead of by position, much like a phone book. In this post, you will learn to create maps, read and update them and loop over them safely. Each idea comes with a short example that you can run yourself.

In the last lesson on slices and arrays in Go, you stored items by index. Maps solve a different problem. You will also use the comma ok pattern. It looks a lot like the error checks from writing and calling functions in Go.

What Are Go Maps?

A map is a collection of key and value pairs. The key is the label you search by, and the value is the data you get back. For example, in a phone book the name is the key and the number is the value.

Go maps find a value by its key very fast, even with millions of entries. So whenever you think “look up X by Y”, a map is usually the right tool.

Creating Go Maps

There are two ways to create a map. Both give you a map that is ready for new keys.

Using a Map Literal

ages := map[string]int{
	"Asha": 28,
	"Ravi": 34,
}

Read map[string]int as “a map from string keys to int values”. Each line inside the braces adds one pair. Also, note the comma after the last pair, because Go requires it.

Using make

stock := make(map[string]int)
stock["pens"] += 10
stock["pens"] += 5
fmt.Println(stock["pens"]) // 15

The make function creates an empty map that is ready to use. Here += works even on a new key, since a missing key starts at its zero value.

Adding, Updating and Reading Values

ages["Meera"] = 25 // add a new key
ages["Ravi"] = 35  // update an existing key

fmt.Println(ages["Ravi"], len(ages)) // 35 3
fmt.Println(ages["Kiran"])           // 0

The same square bracket syntax both adds and updates. However, reading a missing key like “Kiran” does not crash. Instead, Go quietly returns the zero value, which is 0 for an int.

Checking if a Key Exists in Go Maps

That quiet zero creates a problem. Did Kiran never exist, or is his age really 0? To find out, ask for a second value called ok.

age, ok := ages["Kiran"]
fmt.Println(age, ok) // 0 false

if a, ok := ages["Asha"]; ok {
	fmt.Println("Asha is", a)
}
// Asha is 28

Go developers call this the comma ok idiom. The ok value is true only when the key is really there. The diagram below shows both lookups side by side.

Go Maps diagram showing a found key and a missing key with the comma ok check

A found key returns its value and true, while a missing key returns the zero value and false.

Deleting Keys and Counting Items

delete(ages, "Meera")
fmt.Println(len(ages)) // 2

The delete function removes a key and its value. If the key does not exist, nothing happens, so you never need to check first. Then len tells you how many pairs remain.

Looping Over Go Maps

for name, age := range ages {
	fmt.Println(name, age)
}
// Asha 28 and Ravi 35, in any order

Range gives you each key and value. But watch out, because the order changes from run to run on purpose. If you need a fixed order, collect the keys in a slice and sort them first.

Counting Words: A Real Go Maps Example

words := []string{"go", "is", "fun", "go", "go"}
counts := map[string]int{}

for _, w := range words {
	counts[w]++
}
fmt.Println(counts["go"], counts["fun"]) // 3 1

This small pattern appears in real projects all the time. For instance, you can count page visits, votes or log errors the same way.

Common Mistakes with Go Maps

Error you seeWhy it happensHow to fix it
panic: assignment to entry in nil mapThe code wrote to a map declared with var but never created.Create it with make or {}.
invalid map key type []intSlices cannot be keys.Use a string, number or struct.
Wrong value, no errorA missing key returned zero.Use the comma ok check.

The nil map panic is the classic one. A plain var m map[string]int can be read, but it cannot be written to. Map questions like this are common in my Go interview questions and answers, so test yourself there.

Official Resources

These pages come straight from the Go team, so they are always accurate and up to date.

Quick Recap

  • Go maps store key and value pairs, like a phone book.
  • Create them with a literal or make, never with a bare var.
  • A missing key returns the zero value, so use value, ok := m[key].
  • Remove pairs with delete and count them with len.
  • Loop order is random, so sort the keys when order matters.

What’s Next?

Maps hold many values of one type. Next, we will group different kinds of data into one custom type using structs.

Coming soon: Go Structs Explained for Beginners