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
+20.7k Golang : Convert PNG transparent background image to JPG or JPEG image
+39k Golang : How to iterate over a []string(array)
+11k Golang : How to determine a prime number?
+8.8k Golang : Sort lines of text example
+20.1k Golang : Determine if directory is empty with os.File.Readdir() function
+11.1k CodeIgniter : How to check if a session exist in PHP?
+21.7k Golang : Setting up/configure AWS credentials with official aws-sdk-go
+16.6k Golang : Gzip file example
+14.8k Golang : Submit web forms without browser by http.PostForm example
+6.3k Golang : Selection sort example
+15.7k Golang : Get digits from integer before and after given position example
+9.7k Golang : interface - when and where to use examples