In Go, you can access the value associated with a specific key in a map by using the key itself as an index. Here is an example:
package main
import "fmt"
func main() {
// Create a map
m := make(map[string]int)
// Add key-value pairs to the map
m["apple"] = 1
m["banana"] = 2
m["orange"] = 3
// Access the value associated with a specific key
fmt.Println(m["banana"]) // Output: 2
// You can also use the "comma ok" idiom to check if the key exists
value, ok := m["apple"]
if ok {
fmt.Println(value) // Output: 1
} else {
fmt.Println("Key does not exist")
}
}
In this example, we create a map m
where string keys are associated with integer values. We add some key-value pairs to the map. To access the value associated with a specific key, we simply use m[key]
. If the key exists, it will return the value; otherwise, it will return the zero value for the value type (0 in this case for int
).
Additionally, we can use the "comma ok" idiom to check if a key exists in the map. This is useful when you want to distinguish between a missing key and a zero value associated with the key. In the example above, we check if the key "apple" exists in the map using ok
and print the associated value if it does.