Go map
Go 的 map 按鍵存值,比如 map[string]int,用 make 建立;v, ok := m[k] 能判斷鍵在不在,delete(m, k) 刪除,遍歷順序是隨機的。
切片按下標 0、1、2 找元素。很多時候想按名字找:蘋果多少錢、小林考了幾分。這就是 map:一個鍵對應一個值。
1package main2 3import "fmt"4 5func main() {6 prices := map[string]int{7 "蘋果": 5,8 "牛奶": 12,9 "麵包": 8,10 }11 fmt.Println(prices["牛奶"])12 fmt.Println(prices)13}
12 map[牛奶:12 蘋果:5 麵包:8]
map[string]int 是「鍵是 string、值是 int 的 map」。花括號裡每一項寫成 鍵: 值,每行末尾都要有逗號(最後一行也要)。prices["牛奶"] 按鍵取值。
| 鍵 | 值 |
|---|---|
"蘋果" | 5 |
"牛奶" | 12 |
"麵包" | 8 |
fmt.Println 顯示整個 map 時,寫成 map[鍵:值 …],鍵排好了順序。
注意: 漢字按編碼排,不是按拼音或筆畫。
map[string]int 裡的 string 和 int 各說的是什麼?
map[鍵的型別]值的型別:方括號裡是鍵的型別,後面是值的型別。prices["牛奶"] 用字串當鍵,取出來的是 int。存、改和 len
m[鍵] = 值 存一項:鍵還沒有就加進去,已經有了就改掉原來的值。len(m) 是有幾項。空 map 用 make 建:
1package main2 3import "fmt"4 5func main() {6 stock := make(map[string]int)7 stock["鉛筆"] = 408 stock["橡皮"] = 159 fmt.Println(stock, len(stock))10 11 stock["鉛筆"] = 3512 stock["橡皮"] += 1013 fmt.Println(stock, len(stock))14}
map[橡皮:15 鉛筆:40] 2 map[橡皮:25 鉛筆:35] 2
同一個鍵只有一項,所以改了「鉛筆」以後,還是 2 項。
這段程式顯示什麼?
1package main2 3import "fmt"4 5func main() {6 m := map[string]int{"a": 1}7 m["b"] = 28 m["a"] = 109 fmt.Println(len(m), m["a"])10}
m["b"] = 2 加了一項;m["a"] = 10 的鍵已經有了,只是把值改掉,不會多一項。所以一共 2 項,m["a"] 是 10。取一個不存在的鍵
取一個 map 裡沒有的鍵,不會出錯,得到的是值型別的零值:int 是 0,string 是 ""。
這段程式顯示什麼?
1package main2 3import "fmt"4 5func main() {6 votes := map[string]int{}7 votes["紅"]++8 votes["藍"]++9 votes["紅"]++10 fmt.Println(votes["紅"], votes["綠"], len(votes))11}
votes["紅"]++ 第一次時,「紅」不存在,讀到零值 0,加 1 存回去。所以「紅」是 2、「藍」是 1。讀 votes["綠"] 得到 0,但只是讀,不會把「綠」加進 map,所以一共 2 項。可是 0 也可能是真的存了 0。要分清「存的是 0」和「根本沒有」,用兩個變數接:
1package main2 3import "fmt"4 5func main() {6 stock := map[string]int{"鉛筆": 40, "尺子": 0}7 8 n, ok := stock["尺子"]9 fmt.Println(n, ok)10 n, ok = stock["膠水"]11 fmt.Println(n, ok)12 13 if n, ok := stock["鉛筆"]; ok {14 fmt.Println("鉛筆還有", n, "支")15 }16}
0 true 0 false 鉛筆還有 40 支
ok 是 true 說明這個鍵在 map 裡。最後一種寫法很常見:if 帶初始化,在 if 裡用 n。
查庫存
✓寫好 check:商品在 stock 裡,返回 有貨;不在,返回 沒有這個商品。注意「尺子」存的是 0,它也算在 map 裡,返回 有貨(這一題只管在不在)。
有貨 有貨 沒有這個商品
1package main2 3import "fmt"4 5func check(stock map[string]int, item string) string {6 return ""7}8 9func main() {10 stock := map[string]int{"鉛筆": 40, "尺子": 0}11 fmt.Println(check(stock, "鉛筆"))12 fmt.Println(check(stock, "尺子"))13 fmt.Println(check(stock, "膠水"))14}
delete:刪掉一項
delete(m, 鍵) 刪掉一項。刪一個不存在的鍵也不會出錯:
1package main2 3import "fmt"4 5func main() {6 cart := map[string]int{"蘋果": 3, "牛奶": 1, "麵包": 2}7 delete(cart, "牛奶")8 delete(cart, "雞蛋")9 fmt.Println(cart, len(cart))10}
map[蘋果:3 麵包:2] 2
這段程式顯示什麼?
1package main2 3import "fmt"4 5func main() {6 m := map[string]int{"x": 1, "y": 2}7 delete(m, "x")8 delete(m, "z")9 _, ok := m["x"]10 fmt.Println(len(m), ok)11}
ok 是 false。遍歷的順序不固定
for k, v := range m 能走過每一項。但是 map 不記順序:真 Go 每次執行的順序都可能不一樣(Go 故意打亂,免得有人依賴它)。這個網站為了方便單步,順序是固定的,可別當真。
只要結果和順序無關,直接遍歷沒問題,比如求總數。要按順序顯示,先把鍵放進切片排好序,再按這個順序取值:
1package main2 3import (4 "fmt"5 "slices"6)7 8func main() {9 scores := map[string]int{"小林": 88, "阿明": 92, "大衛": 75}10 11 total := 012 for _, v := range scores {13 total += v14 }15 fmt.Println("總分", total)16 17 var names []string18 for name := range scores {19 names = append(names, name)20 }21 slices.Sort(names)22 for _, name := range names {23 fmt.Println(name, scores[name])24 }25}
總分 255 大衛 75 小林 88 阿明 92
for name := range scores 只要鍵。slices.Sort 把切片從小到大排好,要 import "slices"。
想按名字的順序顯示 map 裡的每一項,該怎麼做?
range 的順序都可能不一樣,第二遍也不例外。要固定的順序,就自己把鍵排好。寫 nil map 會 panic
只宣告不建的 map 是 nil。讀它沒問題(得到零值),往裡寫就會 panic:
1package main2 3import "fmt"4 5func main() {6 var counts map[string]int7 fmt.Println(counts["a"], len(counts))8 counts["a"] = 19 fmt.Println(counts)10}
0 0
panic: assignment to entry in nil map
goroutine 1 [running]:
main.main(...)
/tmp/sandbox/prog.go:8 +0x1d
exit status 2發生了什麼: map 還沒有 make 就往裡寫。先 m := make(map[…]…) 或寫成 map[…]…{}。
assignment to entry in nil map:往一個 nil map 裡存東西。var counts map[string]int 只有一個空名字,背後還沒有 map。用 make(map[string]int) 或者 map[string]int{} 建好再存。
var m map[string]intm["a"] = 1 → panic背後還沒有 mapm := make(map[string]int)m["a"] = 1 → map[a:1]可以存了修好它:寫進 nil map
✓addAll 把每樣東西的數量記進 map,可是程式一執行就 panic。改好它,讓它顯示 map[牛奶:2 麵包:1] 和 map[雞蛋:1]。
map[牛奶:2 麵包:1] map[雞蛋:1]
1package main2 3import "fmt"4 5func addAll(items []string) map[string]int {6 var cart map[string]int7 for _, it := range items {8 cart[it]++9 }10 return cart11}12 13func main() {14 fmt.Println(addAll([]string{"牛奶", "麵包", "牛奶"}))15 fmt.Println(addAll([]string{"雞蛋"}))16}
var counts map[string]int 之後,讀 counts["a"] 會怎樣?
int 是 0。只有往裡寫才會 panic。數單詞
把 map 當計數器,是最常見的用法之一:鍵是單詞,值是出現了幾次。
1package main2 3import "fmt"4 5func main() {6 words := []string{"蘋果", "香蕉", "蘋果", "橙子", "蘋果", "香蕉"}7 counts := make(map[string]int)8 for _, w := range words {9 counts[w]++10 }11 fmt.Println(counts)12 fmt.Println("蘋果出現了", counts["蘋果"], "次")13}
map[橙子:1 蘋果:3 香蕉:2] 蘋果出現了 3 次
counts[w]++ 不用先判斷鍵在不在:不在的時候讀到 0,加 1 正好。點單步,看 map 裡的項一個個多起來、數一個個變大。第 9 課會學怎麼把一句話切成單詞。
把這幾行排好,數出每個單詞出現了幾次,程式顯示 map[a:2 b:1]。
}for _, w := range words {counts := make(map[string]int)counts[w]++
map[a:2 b:1]
make 建好 map,再 range 一個個單詞,counts[w]++ 給它加 1。沒有的鍵讀到 0,加 1 正好。統計投票
✓寫好 tally:數一數每個名字得了幾票,回傳一個 map。main 數兩組票,應該顯示 map[Ann:3 Bo:1 Cy:1] 和 map[Bo:2]。
map[Ann:3 Bo:1 Cy:1] map[Bo:2]
1package main2 3import "fmt"4 5func tally(votes []string) map[string]int {6 return nil7}8 9func main() {10 fmt.Println(tally([]string{"Ann", "Bo", "Ann", "Cy", "Ann"}))11 fmt.Println(tally([]string{"Bo", "Bo"}))12}
這一課學會了
map[string]int{…}或make(map[string]int)建 map;m[k] = v存或改,m[k]取,len(m)是項數。- 取不存在的鍵得到零值;
v, ok := m[k]的ok說明鍵在不在。 delete(m, k)刪掉一項。- 遍歷 map 的順序真 Go 每次不一樣:要按順序顯示,先把鍵放進切片
slices.Sort排好。fmt.Println(m)會把鍵排好序。 - 只宣告的 map 是
nil,讀可以,寫會 panic:assignment to entry in nil map。 counts[w]++數東西,不用先判斷鍵在不在。