{"id":2216,"date":"2020-06-09T14:33:46","date_gmt":"2020-06-09T09:03:46","guid":{"rendered":"https:\/\/golangbyexamples.com\/?p=2216"},"modified":"2020-06-09T14:33:58","modified_gmt":"2020-06-09T09:03:58","slug":"check-key-exists-map-golang","status":"publish","type":"post","link":"https:\/\/golangbyexamples.com\/check-key-exists-map-golang\/","title":{"rendered":"An efficient way to check if a key exists in a Map in Go (Golang)"},"content":{"rendered":"\n
Below is the format to check if a key exist in the map<\/p>\n\n\n\n
val, ok := mapName[key]<\/code><\/pre>\n\n\n\nThere are two cases<\/p>\n\n\n\n
- If the key exists val <\/strong>variable be the value of the key in the map and ok <\/strong>variable will be true<\/li><\/ul>\n\n\n\n
- If the key doesn’t exist val<\/strong> variable will be default zero value of value type and ok <\/strong>variable will be false<\/li><\/ul>\n\n\n\n
Let’s see an example<\/p>\n\n\n\n
package main\n\nimport \"fmt\"\n\nfunc main() {\n \/\/Declare\n employeeSalary := make(map[string]int)\n\n \/\/Adding a key value\n employeeSalary[\"Tom\"] = 2000\n fmt.Println(\"Key exists case\")\n val, ok := employeeSalary[\"Tom\"]\n fmt.Printf(\"Val: %d, ok: %t\\n\", val, ok)\n fmt.Println(\"Key doesn't exists case\")\n\n val, ok = employeeSalary[\"Sam\"]\n fmt.Printf(\"Val: %d, ok: %t\\n\", val, ok)\n}<\/code><\/pre>\n\n\n\nOutput<\/strong><\/p>\n\n\n\nKey exists case\nVal: 2000, ok: true\nKey doesn't exists case\nVal: 0, ok: false<\/code><\/pre>\n\n\n\nIn above program when key exists then val<\/strong> variable is set to the actual value which is 2000 here\u00a0 and ok<\/strong> variable is true. When key doesn’t exist the val<\/strong> variable is set to 0 which is default zero value of int and ok<\/strong> variable is false. This ok<\/strong> variable is the best way to check if the key exists in a map or not<\/p>\n\n\n\nIn case we only want to check if a key is present and val is not needed, then blank identifier i.e “_” can be used in place of val.<\/p>\n\n\n\n
_, ok = employeeSalary[\"Sam\"]<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"Below is the format to check if a key exist in the map There are two cases If the key exists val variable be the value of the key in the map…<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"spay_email":"","footnotes":"","jetpack_publicize_message":"","jetpack_is_tweetstorm":false},"categories":[1],"tags":[297,3,4],"class_list":["post-2216","post","type-post","status-publish","format-standard","hentry","category-tech","tag-exists","tag-go","tag-golang"],"yoast_head":"\n
An efficient way to check if a key exists in a Map in Go (Golang) - Welcome To Golang By Example<\/title>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\n\t\n\t\n