Beginner Fundamentals
Maps
A map stores key-value pairs and lets you look up a value quickly by its key. Keys are unique within a map.
Creating a map
Use make or a literal.
ages := make(map[string]int)
ages["Ada"] = 36
ages["Alan"] = 41
fmt.Println(ages) // map[Ada:36 Alan:41]
Literal form:
scores := map[string]int{
"math": 90,
"science": 85,
}
Accessing values
Reading a missing key returns the value type’s zero value.
fmt.Println(scores["math"]) // 90
fmt.Println(scores["history"]) // 0 (not present)
The comma-ok idiom
To tell a real zero from a missing key, use the second return value.
value, ok := scores["history"]
if ok {
fmt.Println("Found:", value)
} else {
fmt.Println("Not present")
}
delete
Remove a key with the built-in delete.
delete(scores, "science")
fmt.Println(scores) // map[math:90]