Go: Maps explained

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

Basics

m := make(map[string]float64)

m["pi"] = 3.1416

fmt.Println(m) // "map[pi:3.1416]"

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

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

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

delete(m, "pi")
fmt.Println(m) // "map[]"

Literals

m := map[string]float64{
        "e":  2.71828,
        "pi": 3.1416,
}

Size

n := len(m) // n == number of elements in m

Iteration

for key, value := range m {
        fmt.Println(key, ": ", value)
}

Implementation

Comments

Be the first to comment!