{"id":5960,"date":"2021-07-11T12:12:28","date_gmt":"2021-07-11T06:42:28","guid":{"rendered":"https:\/\/golangbyexamples.com\/?p=5960"},"modified":"2021-07-12T10:26:27","modified_gmt":"2021-07-12T04:56:27","slug":"check-map-key-golang","status":"publish","type":"post","link":"https:\/\/golangbyexamples.com\/check-map-key-golang\/","title":{"rendered":"How to check if a map contains a key in Go (Golang)"},"content":{"rendered":"\n
Below is the format to check if a key exists 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>
- If the key doesn\u2019t 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\u2019s 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 the above program when a key exists then val<\/strong> variable is set to the actual value which is 2000 here and ok variable is true. When the key doesn\u2019t exist the val variable is set to 0 which is the 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 \u201c_\u201d can be used in place of val.<\/p>\n\n\n\n
_, ok = employeeSalary[\"Sam\"]<\/code><\/pre>\n\n\n\n