Knaph

Maps

Maps

A map is Go's key-value type — the equivalent of a Python dict:

ages := map[string]int{
	"Ada":   36,
	"Grace": 85,
}
 
fmt.Println(ages["Ada"]) // 36

Add or update a key with plain assignment, no append-style reassignment needed (unlike slices, a map is a reference type that's already safe to mutate in place):

ages["Haleh"] = 34

The two-value lookup

Looking up a missing key doesn't panic or return an error — it silently returns the value type's zero value, which is genuinely dangerous if you don't know to check for it:

fmt.Println(ages["Nobody"]) // 0 — looks like a real age!

The fix is the two-value form, the same value, ok pattern you saw with if:

age, ok := ages["Nobody"]
if !ok {
	fmt.Println("not found")
}

You'll write this constantly enough that it becomes reflexive — any time a missing key is meaningfully different from a zero value, use the two-value form.

Deleting and iterating

delete(ages, "Ada")
 
for name, age := range ages {
	fmt.Println(name, age)
}

One thing to know up front: map iteration order is randomized on purpose, on every run. If you need a stable order, sort the keys yourself first — Go deliberately doesn't give you a stable default, specifically so nobody accidentally depends on an ordering that was never guaranteed.

Sign in to track your progress through this course.

Ask an AI

Open a ready-made prompt in ChatGPT or Claude — just press Enter.

SummarizeChatGPTClaude
Ask me questionsChatGPTClaude
Let's learn togetherChatGPTClaude