Go by Example

Maps

Key-value stores with make, literals, get/set/delete, the comma-ok idiom, and range iteration.

A map is Go's built-in key-value type. Keys must be comparable; if the key type is an interface, its dynamic value must also be comparable or a map operation can panic. Values can be any type. Reading a missing key returns the zero value - use the comma-ok idiom to distinguish "key is absent" from "value is zero".

Create a map with make or a map literal. Set, get, and delete entries with simple syntax.

package main
 
import "fmt"
 
func main() {
    ages := map[string]int{"Alice": 30}
    ages["Carol"] = 28
    fmt.Println(ages["Alice"]) // 30
    delete(ages, "Alice")
    fmt.Println(len(ages)) // 1
}

Reading a missing key returns the zero value of the value type - 0 for integers, "" for strings. The comma-ok idiom distinguishes "key is absent" from "value happens to be zero".

package main
 
import "fmt"
 
func main() {
    scores := map[string]int{"Alice": 0}
 
    // Both return 0 - how do you tell them apart?
    a := scores["Alice"]   // 0 (present, value is zero)
    b := scores["Bob"]     // 0 (absent)
    fmt.Println(a, b)      // 0 0
 
    // Comma-ok tells you definitively
    v, ok := scores["Alice"]
    fmt.Println(v, ok) // 0 true
 
    v, ok = scores["Bob"]
    fmt.Println(v, ok) // 0 false
}

range iterates over a map's key-value pairs. The iteration order is unspecified and is not guaranteed to be the same from one iteration to the next, so do not rely on it.

package main
 
import "fmt"
 
func main() {
    capitals := map[string]string{"France": "Paris", "Japan": "Tokyo"}
 
    for country, city := range capitals {
        fmt.Printf("%s: %s\n", country, city)
    }
    // Order varies every run
}

In production

Maps are not safe for concurrent writes or for reading while another goroutine writes. Protect a shared map with sync.RWMutex; use sync.Map only when its specialized access patterns fit. A missing key returns the value type's zero value, so use comma-ok when zero is a valid stored value.

Enjoyed this? Get more software craft delivered to your inbox.