Medium10 minGo Fundamentals
UpdatedAug 4, 2026
Edit

Maps and Safe Access

CONCEPTS:Go Maps

Question Variations

  • "How do you distinguish a missing map key from a stored zero value?"
  • "Which types can be Go map keys?"
  • "Is it safe to read and write a map from different goroutines?"
  • "What happens when you read from a nil map?"

Why This Is Asked

Maps are a basic Go collection, but zero-value lookups and concurrency restrictions cause frequent production bugs. This question checks whether you can write correct presence checks and choose an appropriate strategy for shared access.

Key Concepts

  • Map keys must be comparable; slices, maps, and functions cannot be map keys.
  • Reading an absent key returns the value type’s zero value.
  • The comma-ok form reports whether a key was present.
  • Concurrent map writes, or a read concurrent with a write, require synchronization.

Question Variations

  • “How do you distinguish a missing map key from a stored zero value?”
  • “Which types can be Go map keys?”
  • “Is it safe to read and write a map from different goroutines?”
  • “What happens when you read from a nil map?”

Answers by Technology

+ Add Variant
GoImprove this answer ✏️

Expected Answer (Go 1.26.5)

Map keys must be comparable. Reading a missing key is safe and produces the zero value of the value type, so use the comma-ok form when zero could also be a legitimate stored value. A nil map can be read and ranged over, but assigning to one panics.

Regular maps are not safe for concurrent access when a write is involved. Protect shared maps with synchronization, arrange single-goroutine ownership, or choose a suitable concurrent design.

package main

import "fmt"

func main() {
	counts := map[string]int{"ready": 0}

	value, ok := counts["ready"]
	fmt.Println(value, ok) // 0 true

	value, ok = counts["missing"]
	fmt.Println(value, ok) // 0 false

	delete(counts, "ready") // Safe even if the key is absent.
}

Why It Matters

Presence checks avoid confusing “absent” with meaningful zero values such as a count of zero or a disabled feature. Correct map ownership prevents runtime failures and data races in concurrent services.

Common Mistakes

  • Checking only the returned value for presence: A missing key and an explicit zero value are indistinguishable without ok.
  • Writing to a nil map: Initialize it with make or a map literal before assignment.
  • Using a map from multiple goroutines without synchronization: Concurrent access involving writes is unsafe.

Follow-up Questions

  • Can a slice be used as a map key? (Answer: No, slices are not comparable.)
  • What does delete do for a missing key? (Answer: Nothing; it is safe.)