Golang : Check if element exist in map
Key based element search on a map is the most frequent method use to retrieve the associated value. However, there are times when a search will fail and cause panic if the element is not in the map at the first place. The codes below will show you how to check if an element exist in a map or not.
package main
import "fmt"
func main() {
cities := map[string]string{"city1": "New York", "city2": "Portland"}
// ok is boolean
value, ok := cities["city2"] // return value if found or ok=false if not found
if ok {
fmt.Println("value: ", value)
} else {
fmt.Println("key not found")
}
// try something else
if value, ok = cities["city3"]; ok {
fmt.Println("value: ", value)
} else {
fmt.Println("key not found")
}
}
Output :
value: Portland
key not found
Reference :
See also : Golang : How to delete element(data) from map ?
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+31.9k Golang : How to check if slice or array is empty?
+32.4k Golang : Strip slashes from string example
+6.5k Findstr command the Grep equivalent for Windows
+6.4k Golang : Gomobile init produce "iphoneos" cannot be located error
+3.6k MariaDB/MySQL : Form select statement or search query with Chinese characters
+17.3k Golang : convert int to string
+16.8k Golang : Write file with io.WriteString
+42.3k Golang : Read tab delimited file with encoding/csv package
+20.2k Golang : Securing password with salt
+27.2k Golang : Get and Set User-Agent examples
+9.7k How to tell if a binary(executable) file or web application is built with Golang?
+6.5k Golang : Reverse text lines or flip line order example