Map声明
m := map[string]int{"one":1,"two":2,"three":3}
m1 := map[string]int{}
m1["one"] = 1
m2 = make(map[string]int,10)
package map_test
import "testing"
func TestMapInit(t *testing.T) {
m1 := map[int]int{1:1,2:4,3:9}
t.Log(m1[2])
t.Logf("len m1=%d",len(m1))
m2 := map[int]int{}
m2[4] = 16
t.Logf("len m2=%d",len(m2))
m3 := make(map[int]int, 10)
t.Logf("len m3=%d",len(m3))
}
func TestAccessNotExistingKey(t *testing.T) {
m1 := map[int]int{}
t.Log(m1[1])
m1[2] = 0
t.Log(m1[2])
if v,ok := m1[2]; ok {
t.Logf("key value is :%d",v)
} else {
t.Log("key is not existing in the map")
}
}
在访问的key不存在时,仍会返回零值,不能通过返回nil来判断元素是否存在
Map遍历
func TestMapTravel(t *testing.T) {
m1 := map[int]int{1:1,2:4,3:9}
for k,v := range m1 {
t.Log(k,v)
}
}
Map与工厂模式
- Map 的value可以是一个方法
- 与Go 的Dock type接口方式一起,可以方便的实现单一方法对象的工厂模式
package map_ext
import "testing"
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))
}
实现set
Go的内置集合中没有set实现,可以用map[type]bool
- 元素的唯一性
- 基本操作
1)添加元素
2)判断元素是否存在
3)删除元素
4)元素个数
func TestMapForSet(t *testing.T) {
mySet := map[int]bool{}
mySet[1] = true
if mySet[1] {
t.Log("key is existing")
} else {
t.Log("key is not existing")
}
mySet[2] = true
t.Log(len(mySet))
delete(mySet, 1)
if mySet[1] {
t.Log("key is existing")
} else {
t.Log("key is not existing")
}
}
网友评论