Go语言 遍历map中的键值对

  map 的遍历过程使用 for range 循环完成,代码如下:

package main

import "fmt"

func main() {
    mapNum := make(map[string]int)
    mapNum["key1"] = 1
    mapNum["key2"] = 2
    mapNum["key3"] = 3
    mapNum["key4"] = 4
    //输出map集合key和value
    for k, v := range mapNum {
        fmt.Printf("key:%s value:%d \n", k, v)
    }
    //只输出value
    for _, v := range mapNum {
        fmt.Printf(" value:%d \n", v)
    }
    //只输出key
    for k := range mapNum {
        fmt.Printf("key:%s \n", k)
    }
}

Go语言  遍历map中的键值对

相关推荐