Introducing Radical.sh

Forget Code launches a powerful code generator for building API's

Check if key exists in map in Go

key lookup on Go lang returns a boolean flag indicating whether key is present or not. This value can be checked before using the value returned lookup and value is blank or 0 if key does not exist. Do not check for a empty string or 0 to check if map contains key or not, as they are valid values instead the boolean flag has to be used as shown in example.

Example : Key exists or not
package main

import "fmt"

func main() {
    myMap := make(map[string]string)
    myMap["k1"] = "value1"
    myMap["k2"] = "value2"

    _, ifExists := myMap["k2"]
    fmt.Printf("Key Exists %v \n", ifExists)

    _, ifExists = myMap["k3"]
    fmt.Printf("Key Exists %v", ifExists)
}


Output
Key Exists true
Key Exists false