遍历地图的所有键 [英] Iterating over all the keys of a map

查看:152
本文介绍了遍历地图的所有键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法获得Go语言地图中所有键的列表?元素的数量由 len()给出,但是如果我有像这样的映射:

Is there a way to get a list of all the keys in a Go language map? The number of elements is given by len(), but if I have a map like:

m := map[string]string{ "key1":"val1", "key2":"val2" };

如何迭代所有键?

How do I iterate over all the keys?

推荐答案

https://play.golang.org / p / JGZ7mN0-U-

for k, v := range m { 
    fmt.Printf("key[%s] value[%s]\n", k, v)
}


$对于k:=范围m {
fmt.Printf(key [%]),b $ b

or

for k := range m {
    fmt.Printf("key[%s] value[%s]\n", k, m[k])
}

针对语句的语言规范< 指定第一个值是键,第二个变量是值,但不必存在。

Go language specs for for statements specifies that the first value is the key, the second variable is the value, but doesn't have to be present.

这篇关于遍历地图的所有键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆