Maps in a nutshell

yourbasic.org/golang
Subject catalog drawer

Basics

A map is an unordered collection of key-value pairs, where each key is unique.

var m map[string]int                // m == nil, len(m) == 0
m1 := make(map[string]float64)      // empty map of string-float64 pairs
m2 := make(map[string]float64, 100) // preallocate room for 100 entries
m3 := map[string]float64{
    "e":  2.71828,
    "pi": 3.1416,
}
fmt.Println(len(m1), len(m2), len(m3)) // 0 0 2

Add, find and delete

m := make(map[string]float64)

m["pi"] = 3.1416 // Add a new key-value pair.
fmt.Println(m)   // map[pi:3.1416]

v1 := m["pi"]  // v1 == 3.1416
v2 := m["foo"] // v2 == 0 (zero value)

_, exists := m["pi"] // exists == true
_, exists = m["foo"] // exists == false

if x, ok := m["pi"]; ok { // Prints 3.1416.
    fmt.Println(x)
}

delete(m, "pi") // Delete a key-value pair.
fmt.Println(m)  // map[]

Iterate

m := map[string]float64{
    "e":  2.71828,
    "pi": 3.1416,
}
for key, value := range m { // order not specified 
    fmt.Println(key, value)
}

Implementation details

More nutshells

Core Go concepts: interfaces, slices, maps, for loops, switch statements, packages.

Share this page: