GGistDev

Maps in Go

Maps are hash tables mapping keys to values with average O(1) operations.

Create

Use make for an empty map or a literal for prefilled content. Optionally, preallocate buckets with make(map[K]V, hint).

m := make(map[string]int)              // empty
n := map[string]int{"a": 1, "b": 2}   // literal

Get / presence

Indexing returns the zero value for missing keys. Use the comma-ok idiom to distinguish missing from present-zero.

v := n["a"]            // 1 (zero value if missing)
val, ok := n["x"]     // ok==false if missing
_ = v; _ = val; _ = ok

Set / delete / len

Assign to create or overwrite entries; delete removes a key safely even if absent.

m["count"] = 3
m["count"] = m["count"] + 1

delete(m, "count")
_ = len(m)

Iterate (order not guaranteed)

Map iteration order is randomized by design; do not rely on stable order. Sort keys if you need deterministic order.

for k, v := range n { _ = k; _ = v }

Zero value

Nil maps can be read from but panic on writes. Always initialize before writing.

var z map[string]int   // nil map: reads ok, writes panic
z = make(map[string]int)
z["k"] = 1 // now ok

Set-if-absent

if _, exists := m["key"]; !exists {
    m["key"] = 1
}

Counters and grouping

words := []string{"a","b","a"}
count := map[string]int{}
for _, w := range words { count[w]++ }

Copy vs reference

  • Assignment copies the map header; both refer to same underlying data
  • Use maps.Clone (Go 1.20+) or manual copy if you need a deep copy
clone := maps.Clone(n) // requires import "maps" in Go 1.20+

Concurrency

Maps are not safe for concurrent writes. Use a mutex, sync.Map, or sharded maps for concurrent access patterns.

Summary

  • Use make to initialize before writes
  • Use v, ok := m[k] to test presence
  • Do not rely on iteration order