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
+7.9k Golang : Intercept and compare HTTP response code example
+23.9k Golang : Convert IP address string to long ( unsigned 32-bit integer )
+11.4k Elastic Search : Return all records (higher than default 10)
+34.1k Golang : How to split or chunking a file to smaller pieces?
+19.2k Golang : Pipe output from one os.Exec(shell command) to another command
+4.8k Unix/Linux : How to test user agents blocked successfully ?
+7.8k Golang : Heap sort example
+4.4k Python : Delay with time.sleep() function example
+11.7k Golang : http.Get example
+16.3k Google Chrome : Your connection to website is encrypted with obsolete cryptography
+7.6k Golang : Convert(cast) []byte to io.Reader type
+7.6k Golang : How to find out similarity between two strings with Jaro-Winkler Distance?