Home »
Golang
Check For Specific Elements in a Map in Go
Last Updated : May 27, 2025
In Go, you can check whether a specific key exists in a map using the comma-ok idiom. This helps you avoid confusion between a missing key and a key with a zero value.
Checking for a Specific Key
Use the second return value from map access to determine if a key exists.
Example
This example checks if specific students are present in the map:
package main
import "fmt"
func main() {
attendance := map[string]bool{
"Anjali": true,
"Rohit": true,
}
name := "Rohit"
if present, ok := attendance[name]; ok {
fmt.Printf("%s is marked present: %v\n", name, present)
} else {
fmt.Printf("%s not found in attendance\n", name)
}
name = "Priya"
if present, ok := attendance[name]; ok {
fmt.Printf("%s is marked present: %v\n", name, present)
} else {
fmt.Printf("%s not found in attendance\n", name)
}
}
When executed, this program outputs:
Rohit is marked present: true
Priya not found in attendance
Check Before Accessing Value
It’s a good practice to check for existence before using the value, especially when zero values are meaningful.
Example
This example shows how to handle such a case with student marks:
package main
import "fmt"
func main() {
marks := map[string]int{
"Amit": 78,
"Neha": 92,
}
name := "Neha"
if score, exists := marks[name]; exists {
fmt.Printf("Marks of %s: %d\n", name, score)
} else {
fmt.Printf("No record found for %s\n", name)
}
name = "Kunal"
if score, exists := marks[name]; exists {
fmt.Printf("Marks of %s: %d\n", name, score)
} else {
fmt.Printf("No record found for %s\n", name)
}
}
When executed, this program outputs:
Marks of Neha: 92
No record found for Kunal
Why Use the Comma-ok Idiom?
If your map's value type has a default zero value (like 0
for int
or ""
for string
), accessing a non-existing key may return the zero value, making it hard to distinguish from an actual entry with that value. The comma-ok idiom solves this by confirming the presence of the key.
Example
package main
import "fmt"
func main() {
balance := map[string]int{
"Delhi": 0,
"Mumbai": 200,
}
city := "Delhi"
value, ok := balance[city]
if ok {
fmt.Printf("%s has a balance of ₹%d\n", city, value)
} else {
fmt.Printf("%s not found in balance records\n", city)
}
city = "Chennai"
value, ok = balance[city]
if ok {
fmt.Printf("%s has a balance of ₹%d\n", city, value)
} else {
fmt.Printf("%s not found in balance records\n", city)
}
}
When executed, this program outputs:
Delhi has a balance of ₹0
Chennai not found in balance records
Exercise
Select the correct answer for each question about checking for specific elements in Go maps.
- What does the second value in a map lookup represent?
- How would you check if a key exists in a map?
- What is returned when a key is not found in the map?
Advertisement
Advertisement