Find a key in a map

yourbasic.org/golang

When you index a map in Go you get two return values; the second one (which is optional) indicates if the key exists.

If the key doesn’t exist, the first value will be the default zero value.

m := map[string]float64{"pi": 3.14}

v1 := m["pi"]  // v1 == 3.14
v2 := m["foo"] // v2 == 0.0

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

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

Count elements in a map

The call len(m) returns the number of key-value pairs in m.

m := map[string]int{
    "key1": 1,
    "key2": 10,
    "key3": 100,
}
fmt.Println(len(m))  // 3

Check if a map is empty

In particular, you can use the len function to check if a map is empty.

if len(m) == 0 {
    // m is empty
}

Further reading

Maps in a nutshell

Share this page: