go 的map

2019-05-11  本文已影响0人  OOM_Killer

map声明

首先是map的声明方式。map的普通声明方式很简单。如下所示,需要注意的是make初始化map的时候是不能初始化len的,而后面的数字初始化的时cap。

func Test_InitMap(t *testing.T){
    m := map[string]int{"one":1,"two":2,"three":3}
    m1 := map[string]int{}
    m2 := make(map[string]int,10) // 这个10是cap

    t.Log(m,m1,m2)
    t.Logf("len m2=%d",len(m2))
}

执行 go test -v xx 打印的结果如下。map用make初始化后,长度是0。也就是没有默认map的。

=== RUN   Test_InitMap
--- PASS: Test_InitMap (0.00s)
    map_test.go:10: map[one:1 three:3 two:2] map[] map[]
    map_test.go:11: len m2=0
PASS

map中取不存在的值

对一个初始化后的map,取不存在的key的时候,是不会报错的,反而会返回一个空值,所以想要知道map中检测值存在否需要使用ok-patten的方式来确定

func Test_MapNotExistingKey(t *testing.T){
    m1 := map[int]int{}
    t.Log(m1[2])   // 不存在的就会赋0或空
    m1[2] = 0
    t.Log(m1[2])

    if v,ok := m1[3];ok{
        t.Log("值存在,v为:",v)
    }else{
        t.Log("值不存在")
    }
}

打印的结果为

=== RUN   Test_MapNotExistingKey
--- PASS: Test_MapNotExistingKey (0.00s)
    map_test.go:16: 0
    map_test.go:18: 0
    map_test.go:23: 值不存在
PASS

map的高阶用法-工厂模式

map的value可以是一个方法。如下所示

func Test_MapWithFuncValue(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   Test_MapWithFuncValue
--- PASS: Test_MapWithFuncValue (0.00s)
    map_test.go:33: 2 4 8
PASS

map实现set功能

set可以保证元素的唯一性。可以 map[type]bool , 因为map的key是唯一性的,所以可以使用map的这个特性创建set。delete来删除这个值

func Test_MapForSet(t *testing.T) {
    mySet := map[int]bool{}

    n := 1
    mySet[n] = true

    if mySet[n]{
        t.Logf("%d is existing",n)
    } else {
        t.Logf("%d is not existing",n)
    }

    delete(mySet,1)

    if mySet[n]{
        t.Logf("%d is existing",n)
    } else {
        t.Logf("%d is not existing",n)
    }
}
上一篇 下一篇

猜你喜欢

热点阅读