Maps and week 4 review
A slice is accessed by position: element 0, 1, 2. But often you want to look up by a meaningful key: the price of a product by its name, the user by its identifier, how many times each word appears in a text. For that there is the map, a collection of key-value pairs with very fast lookup. In other languages it is called a dictionary or hash table. Today you will learn to create it, query it, modify it, walk over it and avoid its most common mistakes.
Creating and using a map
The type is written map[K]V, where K is the key type and V the value type. It is created with a literal or with make. The key can be of any type comparable with ==: numbers, strings, bools, arrays and simple structs; it cannot be a slice or another map. It is assigned with m[k] = v and removed with delete(m, k). When reading a key that does not exist there is no error: you get the zero value of the type. To tell an absent key from one that holds zero, use the two-value form, value, ok := m[k], where ok says whether the key exists.
package main
import "fmt"
func main() {
stock := map[string]int{
"apple": 10,
"banana": 0,
}
stock["pear"] = 4
stock["apple"]++
fmt.Println(stock["apple"], stock["kiwi"]) // 11 0 (missing key gives zero)
if qty, ok := stock["banana"]; ok {
fmt.Println("banana exists with", qty) // exists with 0
}
if _, ok := stock["kiwi"]; !ok {
fmt.Println("kiwi is not in stock")
}
delete(stock, "pear")
fmt.Println(len(stock)) // 2
}Walking and counting
With for range you walk keys and values, but the order is not guaranteed and in fact changes from one run to another, on purpose, so nobody depends on it. If you need a stable order, extract the keys to a slice, sort them with slices.Sort and walk them. A very typical use of maps is counting frequencies: since a missing key returns zero, you can write counts[word]++ without checking anything. You can also use a map[string]bool or map[string]struct{} as a set to know whether an element was already seen.
package main
import (
"fmt"
"slices"
"strings"
)
func main() {
text := "go is fun and go is fast"
counts := make(map[string]int)
for _, w := range strings.Fields(text) {
counts[w]++
}
keys := make([]string, 0, len(counts))
for k := range counts {
keys = append(keys, k)
}
slices.Sort(keys) // stable order
for _, k := range keys {
fmt.Println(k, counts[k])
}
// and 1, fast 1, fun 1, go 2, is 2
seen := map[int]struct{}{}
for _, n := range []int{3, 1, 3, 2, 1} {
seen[n] = struct{}{}
}
fmt.Println(len(seen)) // 3 unique values
}Common mistakes and review
The most frequent mistake is writing to a nil map. A map declared with var m map[string]int is nil: you can read it, but assigning to it causes a panic. Always create it with make or with a literal. Another mistake is modifying the map from several goroutines at once, which is not safe; we will solve that in week 7. And remember that maps and slices are reference types: passing them to a function does not copy the data, so the function can modify them. In week 4 you have seen arrays, slices with append and copy, and maps; with these three structures most data problems are solved.
- map[K]V: comparable key, value of any type.
- A missing key gives the zero value; use v, ok := m[k] to know if it exists.
- delete(m, k) removes; the range order is not guaranteed.
- A nil map can be read but not written.
- A map is not safe for concurrent writes.
理解度チェック
問題 1 / 6What value does m["x"] give if the key does not exist in a map[string]int?
✎ マイノート
このブラウザにのみ保存されます。ログインするとアカウントに保存できます。0/5000 文字