Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

A map in Go is a built-in, unordered data structure that implements a hash table, mapping unique keys of a specific type to values of a specific type. It is a reference type, meaning a map variable holds a pointer to the underlying runtime data structure (hmap).

Initialization and Syntax

The zero value of a map is nil. A nil map has no keys, and attempting to write to it will trigger a runtime panic. Maps must be initialized using the make built-in function or a map literal before inserting elements.
// Declaration (Zero value is nil; writes will panic)
var m1 map[string]int

// Initialization via make (Ready for reads and writes)
m2 := make(map[string]int)

// Initialization with a capacity hint (Optimizes memory allocation)
m3 := make(map[string]int, 100)

// Initialization via map literal
m4 := map[string]int{
    "alpha": 1,
    "beta":  2,
}

Key Constraints

Map keys must be of a comparable type. The Go runtime must be able to evaluate == and != on the keys to resolve hash collisions.
  • Valid Key Types: Booleans, numeric types, strings, pointers, channels, and structs or arrays containing only comparable types.
  • Interface Keys: Interface types are valid at compile time. However, if the dynamic value stored inside the interface at runtime is uncomparable (such as a slice or a map), it will trigger a runtime panic.
  • Invalid Key Types: Slices, maps, and functions (these will cause a compile-time error).
Values, however, can be of any type, including other maps or slices.

Core Operations

Map operations are handled via built-in syntax and functions. If you attempt to retrieve a key that does not exist, Go does not return an error; instead, it returns the zero value for the map’s value type.
m := make(map[string]int)

// Insert or Update
m["route"] = 66
m["speed"] = 55

// Retrieve
val := m["route"] // val is 66
missing := m["unknown"] // missing is 0 (zero value for int)

// Length (Returns the number of key-value pairs currently in the map)
count := len(m) // count is 2

// Delete (Safe to call even if the key does not exist)
delete(m, "route")

// Clear (Introduced in Go 1.21: Removes all elements from the map)
clear(m)

The Comma-Ok Idiom

Because missing keys return the zero value, you cannot rely on the returned value alone to determine if a key exists in the map. Go provides the “comma-ok” idiom to explicitly check for key existence.
val, exists := m["route"]
if exists {
    // Key is present in the map
} else {
    // Key is absent
}

Iteration

Maps are iterated using the for range loop. The iteration order of a map is intentionally randomized by the Go runtime to prevent developers from relying on a specific order, as hash table implementations may change.
for key, value := range m4 {
    fmt.Println(key, value)
}

// Iterating only keys
for key := range m4 {
    fmt.Println(key)
}

Memory and Concurrency Mechanics

  • Concurrency: Standard Go maps are not thread-safe. Concurrent reads are safe, but concurrent reads and writes (or concurrent writes) will result in a fatal runtime panic. For concurrent access, developers must wrap the map in a sync.RWMutex or use the sync.Map type.
  • Memory Management: Deleting keys from a map does not shrink the underlying hash table. The memory allocated for the deleted entries is simply marked as empty and retained for future insertions. If a map grows very large and is subsequently emptied (even using clear()), the memory is not released to the garbage collector until the map reference itself is destroyed or reassigned.
Master Go with Deep Grasping Methodology!Learn More