How to check if a map contains a key in Go?


if statements in Go can include both a condition and an initialization statement.
First initialization of two variables - "value" which will receive either the value of "china" from the map and "ok" will receive a bool that will be set to true if "china" was actually present in the map.

Second, evaluates ok, which will be true if "china" was in the map. On that basis print the result.

Using len you can check weather map is empty or not.

Need to work on your code with various hosted apps from anywhere with multiple devices? Take a risk- free trial from a Desktop-as-a-Service provider(DaaS) such as CloudDesktopOnline. For hosted SharePoint and Exchange hosting visit Apps4Rent.com today.

Example

package main

import "fmt"

func main() {
	
	fmt.Println("\n##############################\n")
	strDict := map[string]int {"japan" : 1, "china" : 2, "canada" : 3}
	value, ok := strDict["china"]
	if ok {
			fmt.Println("Key found value is: ", value)
	} else {
			fmt.Println("Key not found")
	}
	
	fmt.Println("\n##############################\n")
	if value, exist := strDict["china"]; exist {
		fmt.Println("Key found value is: ", value)
	} else {
		fmt.Println("Key not found")
	}
	
	fmt.Println("\n##############################\n")
	intMap := map[int]string{
		0: "zero",
		1: "one",
	}
	fmt.Printf("Key 0 exists: %t\nKey 1 exists: %t\nKey 2 exists: %t",
    intMap[0] != "", intMap[1] != "", intMap[2] != "")
	
	fmt.Println("\n##############################\n")	
	t := map[int]string{}
	if len(t) == 0 {
		fmt.Println("\nEmpty Map")
	}
	if len(intMap) == 0 {
		fmt.Println("\nEmpty Map")
	}else{
		fmt.Println("\nNot Empty Map")
	}
	
}

Output

##############################

Key found value is:  2

##############################

Key found value is:  2

##############################

Key 0 exists: true
Key 1 exists: true
Key 2 exists: false
##############################
Most Helpful This Week