Map宣告
m := map[string]int{"one":1,"two":2,"three":3}
m1 := map[string]int{}
m1["one"] = 1
m2 := make(map[string]int, 10 /*Initial Capacity*/)
Map元素的訪問
在訪問的Key不存在時,仍會回傳零值,不能通過回傳nil來判斷元素是否存在
func TestAccessNotExistingKey(t *testing.T) {
m1 := map[int]int{}
t.Log(m1[1])
m1[2] = 0
t.Log(m1[2])
m1[3] = 0 //可以注釋此行代碼查看運行結果
if v,ok:=m1[3];ok{
t.Logf("key 3's value is %d",v)
}else {
t.Log("key 3 is not existing.")
}
}
輸出
=== RUN TestAccessNotExistingKey
--- PASS: TestAccessNotExistingKey (0.00s)
map_test.go:20: 0
map_test.go:22: 0
map_test.go:25: key 3's value is 0
PASS
Process finished with exit code 0
Map 遍歷
示例代碼
m := map[string]int{"one":1,"two":2,"three":3}
for k, v := range m {
t.Log(k, v)
}
func TestTracelMap(t *testing.T) {
m1 := map[int]int{1: 1, 2: 4, 3: 9}
for k, v := range m1 {
t.Log(k, v)
}
}
輸出
=== RUN TestTracelMap
--- PASS: TestTracelMap (0.00s)
map_test.go:34: 1 1
map_test.go:34: 2 4
map_test.go:34: 3 9
PASS
Process finished with exit code 0
示例代碼請訪問: https://github.com/wenjianzhang/golearning
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/33507.html
標籤:Go
下一篇:Effective Go筆記
