To master Go maps, one must understand their initialization nuances, idiomatic usage patterns, and role as the de facto set implementation.

<aside> 🔗

Related Topics:

Initialization

Maps in Go are reference types. A nil map behaves like an empty map when reading, but writing to it causes a runtime panic.

1. Using make

Allocates and initializes a hash map. Use this when you know the capacity or want to initialize an empty map for later writes.

// Initialize with capacity hint (optional but recommended for performance)
m := make(map[string]int, 10)
m["k1"] = 7
m["k2"] = 13

2. Map Literals

Useful for initializing with data.

m := map[string]int{
    "foo": 1,
    "bar": 2,
}

Usage Patterns

Basic Operations

Go maps support built-in operators for adding, getting, and deleting.

m := make(map[string]int)

// Create/Update
m["k1"] = 7

// Read
v := m["k1"] // Returns 7

// Delete
delete(m, "k1")

// Read missing key
v = m["k1"] // Returns zero value (0), no error

The "Comma-ok" Idiom

Since retrieving a missing key returns the zero value, use the second return value to distinguish between "missing" and "zero".

if val, ok := m["k1"]; ok {
    fmt.Println("Key exists:", val)
} else {
    fmt.Println("Key does not exist")
}

Iteration

Map iteration order is randomized by design to prevent reliance on hash stability.

for k, v := range m {
    fmt.Printf("%s -> %d\n", k, v)
}