To check if a key exists in a map in Go, you can use the following syntax:
value, ok := m[key]
m
is the map, key
is the key you want to check, value
is the value associated with the key, and ok
is a boolean variable that indicates whether the key exists in the map or not.
Here is an example:
package main
import "fmt"
func main() {
m := map[string]int{
"apple": 1,
"banana": 2,
"orange": 3,
}
// Check if key "banana" exists
value, ok := m["banana"]
if ok {
fmt.Printf("Value: %d\n", value)
} else {
fmt.Println("Key does not exist")
}
// Check if key "grape" exists
value, ok = m["grape"]
if ok {
fmt.Printf("Value: %d\n", value)
} else {
fmt.Println("Key does not exist")
}
}
Output:
Value: 2
Key does not exist
In this example, the map m
contains key-value pairs. We first check if the key "banana" exists in the map, and if it does, we print its value. Then, we check if the key "grape" exists in the map, and since it doesn't exist, we print a message indicating that the key does not exist.