check if a key does not exist in a map in go

To check if a key does not exist in a map in Go, you can use the following approach:

main.go
_, ok := myMap[key]
if !ok {
    // key does not exist in the map
}
68 chars
5 lines

Here, we use a blank identifier (_) to discard the value associated with the key in the map. Then, we use the second return value from the map access, which is a boolean indicating the existence of the key-value pair in the map. If ok is false, it means that the key does not exist in the map.

gistlibby LogSnag