Maps in Go
| Make and fill | |
| Read with comma-ok | |
| Delete keys | |
| Iterate in random order |
Make and fill
A map stores key and value pairs with fast lookup by key. Declare one with a literal when the content is known, or with make and fill it step by step when keys arrive later.
package main
import "fmt"
func main() {
ages := map[string]int{"Ada": 36, "Bob": 28}
fmt.Println(ages)
scores := make(map[string]int)
scores["Cid"] = 10
fmt.Println(scores)
}
go run main.go
map[Ada:36 Bob:28]
map[Cid:10]
A map declared with plain var and no make is nil: reading it is safe, but writing to it panics. When in doubt, create every map with a literal or with make.
Read with comma-ok
Reading a missing key returns the zero value instead of failing, which makes typos silent. The comma ok form reports whether the key was really there, so always use it when absence matters.
package main
import "fmt"
func main() {
ages := map[string]int{"Ada": 36}
age, ok := ages["Ada"]
fmt.Println(age, ok)
zero, found := ages["Zed"]
fmt.Println(zero, found)
}
36 true
0 false
The second value is true only when the key exists. Branch on it to tell a stored zero apart from a missing entry.
Delete keys
Delete removes a key and its value in one call, and deleting a key that is absent is simply a quiet no op. Maps need no cleanup beyond that: unused entries vanish with the map itself.
package main
import "fmt"
func main() {
ages := map[string]int{"Ada": 36, "Bob": 28}
delete(ages, "Bob")
fmt.Println(ages)
}
map[Ada:36]
There is no error to check here: delete always succeeds. To clear everything at once, simply make a fresh map and let the old one go.
Iterate in random order
Range over a map visits every pair exactly once, but in a fresh random order on each run. That randomness keeps programs honest: any logic that needs order must sort explicitly.
package main
import "fmt"
func main() {
ages := map[string]int{"Ada": 36, "Bob": 28, "Cid": 41}
for name, age := range ages {
fmt.Println(name, age)
}
}
Run this program twice and the lines may swap places. For stable output, collect the keys into a slice, sort the slice, and then read the map in that order.
Next: Functions
Article author: Arthur Isaev