how to check if value exiets in map in go
To check if a value exists in a map in Go, you can use the following steps:
- Access the value using the key from the map.
- Check the second return value (a boolean) from the map access.
Here is an example code snippet that demonstrates how to check if a value exists in a map in Go:
package main
import "fmt"
func main() {
// Create a map with some values
myMap := map[string]int{
"apple": 1,
"banana": 2,
"orange": 3,
}
// Check if a value exists in the map
value, exists := myMap["apple"]
if exists {
fmt.Println("Value exists:", value)
} else {
fmt.Println("Value does not exist")
}
}
In this example, we create a map myMap
with some key-value pairs. We then use the key "apple"
to access the value from the map. The second return value from the map access is assigned to the variable exists
, which will be true
if the key exists in the map and false
otherwise. We can use this boolean value to determine if the value exists in the map or not.