ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

Go (Golang) Tutorial• 6 min read

Maps: Fast Hash Tables & The Comma-Ok Idiom

make(map[K]V), deleting keys, and safely checking existence with comma-ok

Maps are unordered hash tables providing average O(1) key-value lookups. Go uses the "comma-ok" idiom to distinguish between missing keys and keys holding zero values.

The Comma-Ok Idiom

Initialization: userScores := make(map[string]int).

Missing key trap: Accessing a non-existent key in Go returns its zero value (0), NOT an error or null!

Comma-Ok syntax: val, ok := myMap["key"]. ok is true if key exists, false otherwise.

delete(myMap, "key"): Safely removes a key from the map.

Safe Map Key Lookups with Comma-Ok
package main

import "fmt"

func main() {
    rates := map[string]float64{
        "EUR": 1.08,
        "GBP": 1.25,
    }

    // Comma-ok idiom to verify existence
    currency := "JPY"
    if rate, exists := rates[currency]; exists {
        fmt.Printf("%s rate is: %.2f\n", currency, rate)
    } else {
        fmt.Printf("Currency %s is not supported!\n", currency)
    }
}
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

What is the purpose of the second boolean variable in the Go idiom `value, ok := myMap[key]`?