Go🔧Core Languagebeginner
Maps
Go · Core Language · Run with go run
Explanation
A `map[K]V` is Go's built-in hash map. Keys must be `comparable` (no slices, maps, or functions as keys). The zero value of a map is `nil` — attempting to write to a nil map panics. Always initialize with `make` or a literal. The two-value assignment `v, ok := m[key]` safely checks for key presence without panicking on missing keys.
Real-World Scenario
Counting word frequencies in a document: `counts := make(map[string]int)` then `counts[word]++` — the zero value of `int` (0) means missing keys auto-initialize correctly.
Quick Snippet
snippet.go
// Literal initialization
scores := map[string]int{
"Alice": 95,
"Bob": 87,
}
// Safe lookup
score, ok := scores["Charlie"]
if !ok {
fmt.Println("not found")
}
// Delete
delete(scores, "Bob")
// Iterate (order is random)
for name, s := range scores {
fmt.Println(name, s)
}Full Example
maps.go
// Compile: go run maps.go
// Output:
// Alice: 95
// Charlie present: false
// after delete, has Bob: false
// total entries: 1
package main
import "fmt"
func main() {
scores := map[string]int{
"Alice": 95,
"Bob": 87,
}
fmt.Println("Alice:", scores["Alice"])
// Comma-ok lookup — safe check for missing keys
_, ok := scores["Charlie"]
fmt.Println("Charlie present:", ok)
delete(scores, "Bob")
_, hasBob := scores["Bob"]
fmt.Println("after delete, has Bob:", hasBob)
fmt.Println("total entries:", len(scores))
}
Run command
go run maps.go