欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

【go学习笔记】七、Map声明、元素访问及遍历

程序员文章站 2022-03-26 14:06:45
Map声明 Map元素的访问 在访问的Key不存在时,仍会返回零值,不能通过返回nil来判断元素是否存在 输出 Map 遍历 示例代码 输出 示例代码请访问: https://github.com/wenjianzhang/golearning ......

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

示例代码请访问: