To check if a key exists in a map in Go, you can use the comma ok
idiom. Here's an example:
main.go273 chars14 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.
gistlibby LogSnag