一、map定义、访问、遍历
package map_test import "testing" //map func TestMap(t *testing.T) { //定义并初始化 m := map[string]int{"one": 1, "two": 2, "three": 3} t.Log(m["one"]) t.Logf("m len=%d", len(m)) //定义 m1 := map[string]int{} //添加元素 m1["four"] = 4 //使用make定义,合理的初始容量,提交性能 m2 := make(map[string]int, 10) t.Log(m, m1, m2) } //map访问的key不存在是,仍会返回零值,不能通过nil来判断元素是否存在 func TestAccessNotExistingKey(t *testing.T) { //创建map m1 := map[int]int{} t.Log(m1[1]) m1[2] = 0 t.Log(m1[2]) //使用ok判断是否存在 if _, ok := m1[3]; ok { t.Log("key 3 is existing.") } else { t.Log("key 3 is not existing.") } } //遍历 func TestTravelMap(t *testing.T) { m := map[string]int{"one": 1, "two": 2, "three": 3} for key, value := range m { t.Log(key, value) } }
=== RUN TestMap map_test.go:9: 1 map_test.go:10: m len=3 map_test.go:17: map[one:1 three:3 two:2] map[four:4] map[] --- PASS: TestMap (0.00s) === RUN TestAccessNotExistingKey map_test.go:24: 0 map_test.go:26: 0 map_test.go:31: key 3 is not existing. --- PASS: TestAccessNotExistingKey (0.00s) === RUN TestTravelMap map_test.go:39: three 3 map_test.go:39: one 1 map_test.go:39: two 2 --- PASS: TestTravelMap (0.00s) PASS
二、map值使用函数
func TestMapWithFunValue(t *testing.T) { m := map[int]func(op int) int{} m[1] = func(op int) int { return op } m[2] = func(op int) int { return op * op } m[3] = func(op int) int { return op * op * op } t.Log(m[1](2), m[2](2), m[3](2)) }
=== RUN TestMapWithFunValue map_ext_test.go:11: 2 4 8 --- PASS: TestMapWithFunValue (0.00s) PASS
三、map实现set
//map实现set func TestMapForSet(t *testing.T) { mySet := map[int]bool{} //添加 mySet[1] = true n := 6 //判断是否存在 if mySet[n] { t.Logf("%d is existing", n) } else { t.Logf("%d is not existing", n) } // 输出长度 t.Log(len(mySet)) // 删除元素 delete(mySet, 1) }
=== RUN TestMapForSet map_ext_test.go:24: 6 is not existing map_ext_test.go:27: 1 --- PASS: TestMapForSet (0.00s) PASS