Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 147 ยท Collections

Maps

Learn Go maps from scratch - literals and make, the comma-ok lookup, delete, random iteration order, nil map panics, sets with map[T]struct{}, counting and grouping idioms, and concurrency limits.

A map stores key-value pairs and finds a value by its key in constant time on average. It's Go's built-in hash table: the same idea as a dictionary in Python, a HashMap in Java or an object used as a lookup table in JavaScript. Maps are how you count words, index records by ID, cache results and remove duplicates.

The type is written map[K]V: keys of type K, values of type V. This lesson covers creating maps, reading with the "comma ok" idiom, deleting, looping (in random order), the nil-map trap, sets, grouping and counting, maps holding structs and slices, and why maps are not safe to share between goroutines without protection.

Creating maps

You can write a map literal, or create an empty map with make:

Go Map literals and make

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

When you print a map with fmt, the keys come out sorted, which makes output readable and tests stable. That sorting is a nicety of fmt; the map itself has no order, as you'll see shortly.

Keys can be any comparable type: numbers, strings, booleans, pointers, channels, arrays of comparable elements, structs whose fields are all comparable, and interfaces. Slices, maps and functions can't be keys because they can't be compared with ==. Values can be anything.

Reading, writing and the comma-ok idiom

You write with m[key] = value and read with m[key]. Reading a key that is missing doesn't fail: it returns the zero value of the value type. That makes it impossible to tell "stored as zero" from "not there", so Go offers a two-value form:

Go Lookup with comma ok

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The zero-value behavior is a feature, not a bug: counts[word]++ works even on the first sighting of word, because the missing entry reads as 0. We'll use that in a moment.

Deleting

delete(m, key) removes an entry. It does nothing, and doesn't panic, when the key is absent or the map is nil. clear(m) (Go 1.21) removes everything:

Go delete and clear

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Iterating: the order is random on purpose

for k, v := range m visits every entry exactly once, but in an unspecified order that changes from run to run. Go randomizes it deliberately, so nobody writes code that accidentally depends on an order that was never promised. Deleting the entry you are visiting is safe, and entries added during the loop may or may not be visited.

When you need a stable order, collect the keys and sort them. Since Go 1.23 the maps and slices packages (see the slices and maps packages) make that one line:

Go Stable iteration with sorted keys

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Never write tests or output that depend on the order of range over a map. If your program prints in a different order each run, a map loop is the first suspect.

Writing to a nil map panics

A map variable that was declared but never created is nil. Reading from it is fine (you get zero values) but writing panics:

Go Writing to a nil map (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The run prints 0 0 true and then fails with panic: assignment to entry in nil map. Always create the map first with a literal or make. This is a classic bug in structs: a struct field of map type starts out nil, so constructors (see constructors and options) must initialize it.

Sets, counting and grouping

Go has no set type. The idiom is a map with empty-struct values: struct{} takes zero bytes, so only the keys matter. Counting is a map to int, and grouping is a map to a slice:

Go Sets, counting and grouping

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Many programmers use map[T]bool for sets because if seen[x] reads nicely. That works too; struct{} is slightly more memory-friendly and states clearly that only presence matters.

Maps of structs

Map values are not addressable. You can read a struct out of a map, but you can't assign to one of its fields in place:

Go Updating a struct stored in a map (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The compiler says cannot assign to struct field players["p1"].Score in map. There are two standard fixes. Copy the struct out, change it and store it back, or store pointers in the map so that the pointed-to struct can be modified. See structs and pointers for the details:

Go Two ways to update map values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Copying and comparing

Assigning a map copies only the reference, as with slices. Both variables see the same data. To make an independent copy use maps.Clone, and to compare contents use maps.Equal. The == operator works only against nil:

Go Maps are references

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Passing a map to a function therefore lets that function modify your data, without any pointer.

Maps and concurrency

Maps are not safe for concurrent use. If one goroutine writes while any other goroutine reads or writes, the program has a data race, and the runtime may crash it with fatal error: concurrent map writes. Protect shared maps with a sync.Mutex or sync.RWMutex, or use sync.Map for special access patterns. Both are covered in the sync package, and data races shows how to find these bugs.

Go
type SafeCounter struct {
	mu sync.Mutex
	m  map[string]int
}

func (c *SafeCounter) Inc(key string) {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.m[key]++
}

Several goroutines that only read a map that nobody modifies are fine.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does m := map[string]int{}; fmt.Println(m["x"]) print?

    Reading a missing key returns the zero value of the value type, which is 0 for int.
  2. 2. How do you tell a stored zero from a missing key?

    The comma-ok form returns a second boolean that is true only when the key exists.
  3. 3. What happens at var m map[string]int; m["a"] = 1?

    A nil map can be read but not written. The panic message is: assignment to entry in nil map.
  4. 4. Which type is NOT allowed as a map key?

    Keys must be comparable with ==. Slices, maps and functions are not comparable.
  5. 5. What is the iteration order of for k := range m?

    Go deliberately randomizes the order. Sort the keys first when you need a stable order.

Summary

  • A map is map[K]V, created with a literal or make. Keys must be comparable.
  • Missing keys read as the zero value, so use v, ok := m[k] when presence matters.
  • delete removes a key and is safe on missing keys and nil maps; clear empties a map; len counts entries.
  • range order is random. Use slices.Sorted(maps.Keys(m)) for a stable order.
  • Reading a nil map is fine, but writing to one panics. Create maps before use.
  • Idioms: sets with map[T]struct{}, counting with m[k]++, grouping with m[k] = append(m[k], x).
  • You can't assign to a field of a struct inside a map. Copy it out and back, or store pointers.
  • Maps are references: assignment shares data, maps.Clone copies. They are not safe for concurrent writes.

Next: The slices and maps Packages shows the standard helpers that save you from writing these loops by hand.