Home »
Golang
Access Map Elements in Go
Last Updated : May 27, 2025
In Go, you can access elements in a map using the key inside square brackets. If the key exists, the corresponding value is returned. If the key is not present, a zero value for the value type is returned.
Accessing Map Elements by Key
Use the key inside square brackets to retrieve a value from a map.
Example
This example shows how to access values using keys in a map:
package main
import "fmt"
func main() {
countries := map[string]string{
"IN": "India",
"US": "United States",
"FR": "France",
}
fmt.Println("IN:", countries["IN"])
fmt.Println("US:", countries["US"])
fmt.Println("FR:", countries["FR"])
}
When executed, this program outputs:
IN: India
US: United States
FR: France
Accessing a Non-Existing Key
If you try to access a key that doesn't exist, Go returns the zero value for the map's value type.
Example
This example attempts to access a non-existing key:
package main
import "fmt"
func main() {
marks := map[string]int{
"Rahul": 85,
"Sneha": 92,
}
fmt.Println("Marks of Rahul:", marks["Rahul"])
fmt.Println("Marks of Amit:", marks["Amit"]) // Key not present
}
When executed, this program outputs:
Marks of Rahul: 85
Marks of Amit: 0
Using Value with Existence Check
You can use the second return value to check if a key exists in the map.
Example
This example shows how to check if a key exists using the comma-ok idiom:
package main
import "fmt"
func main() {
fruits := map[string]int{
"Apple": 10,
"Banana": 20,
}
qty, exists := fruits["Apple"]
if exists {
fmt.Println("Apple is available with quantity:", qty)
}
qty, exists = fruits["Mango"]
if !exists {
fmt.Println("Mango is not available")
}
}
When executed, this program outputs:
Apple is available with quantity: 10
Mango is not available
Exercise
Select the correct answer for each question about accessing map elements in Go.
- What is returned when you access a non-existent key in a map of type
map[string]int
?
- How can you check if a key exists in a Go map?
- What happens if you try to access a key in a nil map?
Advertisement
Advertisement