← Back to Go Course | Chapter 5: Arrays Slices Maps | Lesson 5 of 7

Maps

A map is like a phone book: you look up a name (the key) and it instantly tells you the matching number (the value), instead of numbering entries 0, 1, 2 like a slice.

Creating a Map

A map associates keys with values, similar to a dictionary in Python or an object in JavaScript. It's created either with make(map[KeyType]ValueType) or a map literal listing initial key-value pairs.

Example: Creating a Map

markup
package main

import "fmt"

func main() {
	prices := map[string]float64{
		"apple":  0.5,
		"banana": 0.25,
	}
	fmt.Println(prices["apple"])
}

The nil Map Trap

A map declared with just 'var m map[string]int' is nil, and while reading from a nil map is safe (it returns the zero value), writing to it causes a runtime panic. This is a very common beginner mistake.

Note: Always initialize a map with make() or a literal before writing to it.

Example: The nil Map Trap

markup
package main

import "fmt"

func main() {
	var scores map[string]int
	fmt.Println("read from nil map is safe:", scores["nobody"])
	scores = make(map[string]int)
	scores["alice"] = 90
	fmt.Println(scores)
}

Checking If a Key Exists

Reading a key that doesn't exist returns the zero value for the map's value type rather than an error, which can be ambiguous. The 'comma ok' form -- value, ok := m[key] -- tells you definitively whether the key was actually present.

Note: Always use the comma-ok form when the zero value is a valid, ambiguous result (like 0 for a real score).

Example: Checking If a Key Exists

markup
package main

import "fmt"

func main() {
	ages := map[string]int{"amit": 30}
	age, ok := ages["priya"]
	fmt.Println("age:", age, "found:", ok)
}
Common Mistakes
  1. Writing to a nil map (declared with 'var m map[K]V' but never initialized with make) which causes a runtime panic.
  2. Assuming maps preserve insertion order when iterating -- Go deliberately randomizes map iteration order.
  3. Reading a missing key and treating the returned zero value as if the key existed, instead of checking the second 'comma ok' return value.
Chapter Summary
  • A map stores key-value pairs, declared as map[KeyType]ValueType.
  • Maps must be initialized with make() or a map literal before you can write to them -- a nil map panics on write.
  • Reading a missing key returns the value type's zero value, not an error, unless you use the comma-ok form.
  • Map iteration order is randomized on purpose by the Go runtime.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.