Map声明
m := map[string]int{"one": 1, "two": 2, "three": 3}
m1 := map[string]int{}
m1["one"] = 1
m2 := make(map[string]int, 10) // 10 is initial capactity
Map元素的访问
在访问的Key不存在时,Map仍然会返回零值,不能通过nil来判断元素是否存在
func TestAccessNotExistingKey(t *testing.T) {
m1 := map[int]int{}
t.Log(m1[1])
m1[2] = 0
t.Log(m1[2])
if v, ok := m1[3]; ok {
t.Logf("Key 3' value is %d\n", v)
} else {
t.Log("Key 3 is not exitsting.")
}
}
Map遍历
func TestTravelMap(t *testing.T) {
m1 := map[int]int{1: 1, 2: 4, 3: 9}
for key, value := range m1 {
t.Logf("key = %d value = %d\n", key, value)
}
}