How to check if a map contains a key in Go

Created
Modified

Use second return value directly in an if statement

If "BST" is indeed present in the map, the body of the if statement will be executed and v will be local to that scope.

package main

import "fmt"

func main() {

  dict := map[string]int{
    "UTC": 0 * 60 * 60,
    "BST": 1 * 60 * 60,
  }

  if _, ok := dict["UTC"]; ok {
    //do something here
    fmt.Println(dict["UTC"])
  }

}
3600

To test for presence in the map without worrying about the actual value, you can use the blank identifier (_) in place of the usual variable for the value.

Check second return value

if statements in Go can include both a condition and an initialization statement.

m := map[string]int{
  "foo": 1, 
  "bar": 2
}
v, ok := m["foo"] // v == 1  ok == true
v, ok = m["foooo"] // v == 0   ok == false
_, ok = m["foo"]  // ok == true

Check for zero value

if the map is nil or does not contain such an entry, a[x] is the zero value for the element type of M.

m := map[string]int{
  "foo": 1
}

v := m["foo"] // v == 1
v = m["fooooo"] // v == 0 (zero value)

Related Tags