Go by Example

Maps

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

A map stores values under keys, like a dictionary. Keys must be values Go can compare with ==; values can be any type. Reading a missing key returns the default for the value type, such as 0 for an integer. Use the two-result form to tell a missing key from a key that stores 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
}

The two-result form returns the value and a boolean that is true when the key exists. This matters when a stored value can itself be zero, such as 0 for an integer or "" for a string.

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

Do not read or write the same map from multiple goroutines at once without coordination. A goroutine is a function running independently from its caller. Use a mutex, a lock that lets only one goroutine access the map at a time, when data must be shared. Use the two-result form when zero is a meaningful value.

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