intermediate18 min

Maps

Go's built-in hash map type, and the comma-ok idiom for checking key existence.

What you'll learn

  • Declare and populate a map with `map[KeyType]ValueType`
  • Use the 'comma-ok' idiom to distinguish a missing key from a zero-value entry
  • Delete a key from a map with the built-in `delete` function

Explanation

A Go map is a built-in hash map, declared as map[KeyType]ValueType, e.g. map[string]int maps strings to ints. You create one with make(map[string]int) or a map literal: ages := map[string]int{"Ada": 30, "Grace": 45}.

Reading a key that doesn't exist doesn't panic -- it returns the zero value for the value type (0 for int, "" for string, and so on). This creates ambiguity: is a value of 0 a real stored value, or a missing key? The comma-ok idiom resolves it: value, ok := ages["Unknown"] -- ok is true only if the key genuinely exists, letting you tell "missing" apart from "present with a zero value."

You remove a key with the built-in delete(map, key) function -- deleting a key that doesn't exist is a safe no-op, not an error.

Iteration order over a map with range is not guaranteed to be consistent between runs -- if you need a predictable order, sort the keys yourself first.

Guided lab

Fill in the blank: comma-ok idiom

GoNot executed
This lab does not run in your browser or on VisaSparkSchools's servers. Read the code, fill in the missing piece, then reveal the completed code and its expected output.

Fill in the missing second variable name for the comma-ok pattern, then predict the output.

package main

import "fmt"

func main() {
	scores := map[string]int{"Ada": 90, "Grace": 85}

	value, ____ := scores["Ada"]
	fmt.Println(value, ____)

	value2, ____2 := scores["Linus"]
	fmt.Println(value2, ____2)
}

Stuck? Get a hint.

Common mistakes

  • Reading a missing map key and assuming a returned zero value means the key exists with that value, instead of checking with the comma-ok idiom.
  • Relying on a consistent iteration order when ranging over a map -- Go deliberately does not guarantee one.
  • Assuming `delete` on a nonexistent key causes an error -- it's actually a safe no-op.

Knowledge check

Knowledge check

1. What does reading a missing key from a Go map return, if you don't use the comma-ok form?
2. What does the second value in `value, ok := myMap[key]` tell you?
3. Is Go map iteration order guaranteed to be consistent?

Takeaway

Use the comma-ok idiom (`value, ok := myMap[key]`) whenever you need to distinguish a missing key from a stored zero value.

Summary

Maps are declared as `map[KeyType]ValueType`; missing keys return a zero value, so use comma-ok to check real existence; `delete` is always safe.

References

Your notes

Notes save automatically.

Finished this lesson?

Mark it complete to track your progress and schedule a future review.

Next: Structs and Methods