check if a key exists in a map in go

To check if a key exists in a map in Go, you can use the comma ok idiom. Here's an example:

main.go
// create a map of string keys and int values
m := map[string]int{
  "one": 1,
  "two": 2,
  "three": 3,
}

// check if key "one" exists in the map using comma ok idiom
if _, ok := m["one"]; ok {
  fmt.Println("Key exists!")
} else {
  fmt.Println("Key does not exist!")
}
273 chars
14 lines

In this example, we create a map called m with three key-value pairs. We then use the comma ok idiom to check if the key "one" exists in the map. The expression _, ok := m["one"] returns two values: the value associated with the key "one", and a boolean indicating whether the key exists in the map. We ignore the value and only use the boolean value by assigning it to the variable ok.

If the key "one" exists in the map, the ok boolean will be true, and the message "Key exists!" will be printed. Otherwise, the ok boolean will be false, and the message "Key does not exist!" will be printed.

related categories

gistlibby LogSnag