Maps
A map stores key-value pairs, declared with map[KeyType]ValueType. Map literals and assignment both use familiar syntax, and looking up a missing key doesn't panic — it just returns the value type's zero value.
main.go
Try it yourself →package main
import "fmt"
func main() {
scores := map[string]int{"Alice": 95, "Bob": 87}
scores["Carol"] = 91
fmt.Println(scores["Alice"])
fmt.Println(scores["Carol"])
}Output
95 91
The comma-ok idiom
Because a missing key silently returns a zero value, Go gives you a second return value to tell the two cases apart: value, ok := m[key] sets ok to false if the key wasn't present, letting you distinguish "key genuinely maps to zero" from "key doesn't exist at all".
main.go
Try it yourself →package main
import "fmt"
func main() {
scores := map[string]int{"Alice": 95, "Bob": 87}
value, ok := scores["Dave"]
fmt.Println(value, ok)
value, ok = scores["Alice"]
fmt.Println(value, ok)
}Output
0 false 95 true
Next: structs — grouping related data together.
Practice exercise
Create a map ages := map[string]int{} (empty), insert "Alice" -> 30, then print ages["Alice"].