In this brief tutorial we’ll explore 2 examples to check if a key is in map in golang, this might be useful for those who want to check map in go for the existence of a key.
Example 1:
if val, ok := dict["foo"]; ok {
//do something here
}
if statements in Go can include both a condition and an initialization statement. The example above uses both:
initializes two variables — val will receive either the value of "foo" from the map or a "zero value" (in this case the empty string) and ok will receive a bool that will be set to true if "foo" was actually present in the map
evaluates ok, which will be true if "foo" was in the map
If “foo” is indeed present in the map, the body of the if statement will be executed and val will be local to that scope.
Example 2:
package main
import "fmt"
func main() {
dict := map[string]int {"foo" : 1, "bar" : 2}
value, ok := dict["baz"]
if ok {
fmt.Println("value: ", value)
} else {
fmt.Println("key not found")
}
}
source: https://stackoverflow.com/questions/2050391/how-to-check-if-a-map-contains-a-key-in-go
Get the book: Learn GO Programming
Other Dev posts you might like:
Discussion