Last updated on Jun 28, 2021 by Suraj Sharma
In this tutorial, you will learn how you can check if a given map contains a key
in Golang
Map in Golang contains key value associative pairs, the index expression of a map
always returns two values, one is the value associated with the key
and another is a bool
value, which is true
if the key
is present in the map, otherwise it is false
.
strMap := make(map[string]string)
strMap["1"] = "One"
fmt.Print(strMap["1"]) // prints "One"
fmt.Print(strMap["2"]) // prints ""
package main
import "fmt"
func main () {
strMap := make(map[string]string)
strMap["1"] = "One"
if val, isKeyExists := strMap["2"]; isKeyExists {
fmt.Printf("key exists: value [%s]", val)
} else {
fmt.Print("key doesn't exist")
}
}
Related Solutions
Rate this post
Suraj Sharma is the founder of Future Gen AI Services. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.