Go Maps
A map is a collection that stores a value under each key. A key finds its value in one lookup.
Make a map and read a value
The make call creates an empty map. A key goes inside square brackets when a value is stored or read.
package main
import "fmt"
func main() {
ages := make(map[string]int)
ages["Ana"] = 22
ages["Bo"] = 31
fmt.Println(ages["Ana"])
fmt.Println(len(ages))
}A missing key reads as zero
A missing key gives the zero value. The comma-ok read adds a bool that tells whether the key was really there.
package main
import "fmt"
func main() {
ages := map[string]int{"Ana": 22}
fmt.Println(ages["Zoe"])
value, ok := ages["Zoe"]
fmt.Println(value, ok)
value, ok = ages["Ana"]
fmt.Println(value, ok)
}Delete removes a key
The delete call takes the map and the key. The length drops by one after the call.
package main
import "fmt"
func main() {
ages := map[string]int{"Ana": 22, "Bo": 31, "Hana": 27}
delete(ages, "Bo")
fmt.Println(len(ages))
fmt.Println(ages)
}A whole map prints in sorted order
The fmt package sorts the keys when it prints a whole map. The printed order stays the same on every run.
package main
import "fmt"
func main() {
ages := map[string]int{"Hana": 27, "Ana": 22, "Bo": 31}
fmt.Println(ages)
}Walk sorted keys for ordered lines
The keys go into a slice first. Sorting that slice fixes the order of the printed lines.
package main
import "fmt"
import "slices"
func main() {
ages := map[string]int{"Hana": 27, "Ana": 22, "Bo": 31}
keys := make([]string, 0, len(ages))
for k := range ages {
keys = append(keys, k)
}
slices.Sort(keys)
for _, k := range keys {
fmt.Println(k+":", ages[k])
}
}Example
package main
import "fmt"
import "slices"
func main() {
words := []string{"go", "web", "go"}
counts := make(map[string]int)
for _, w := range words {
counts[w]++
}
keys := make([]string, 0, len(counts))
for k := range counts {
keys = append(keys, k)
}
slices.Sort(keys)
for _, k := range keys {
fmt.Println(k+":", counts[k])
}
}Key points
- Use make to create an empty map.
- A map type names a key type and a value type.
- Reading a missing key gives the zero value for the value type.
- The comma-ok read gives a bool that reports whether the key was present.
- Use delete to remove a key and its value from a map.
In this example, the loop walks the words slice and adds one to the count for each word. The word go appears twice and the word web appears once. The keys are sorted before printing, so the lines come out in a fixed order.
Note
Ranging a map gives keys in a changing order, so sorting the keys first fixes the order.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Go Playground
Exercise
In value, ok := ages["Zoe"], what does ok report when Zoe is not a key?