Maps Cheatsheet

Creation

  • Make: m := make(map[K]V)
  • Literal: m := map[string]int{"A": 1}
  • Nil: var m map[string]int (Cannot be written to!)

Operations

  • Insert/Update: m[key] = val
  • Get: v := m[key] (Returns zero value if missing)
  • Delete: delete(m, key)
  • Length: len(m)

Comma OK Idiom

if val, ok := m[key]; ok {
    // Exists
}

Constraints

  • Keys: Must be comparable (no slices, maps, or functions).
  • Values: Can be anything.
  • Reference: Maps are passed by reference; functions can mutate them.

Common Patterns

  • Sets: map[T]struct{}
  • Nested Maps: map[K]map[K]V (Must initialize inner map!)
  • Grouping: Using maps to count frequencies or group items by a key.