Iterating over all the keys of a map
有没有办法在Go语言地图中获得所有键的列表?元素的数量由
1 | m := map[string]string{"key1":"val1","key2":"val2" }; |
如何迭代所有键?
play.golang.org http:/ / / / jgz7mn0 U P
1 2 3 4 | for k, v := range m { fmt.Printf("key[%s] value[%s] ", k, v) } |
或
1 2 3 4 | for k := range m { fmt.Printf("key[%s] value[%s] ", k, m[k]) } |
Go语言的语句应该提醒的是,
这里是一些简单的方法来获得
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | // Return keys of the given map func Keys(m map[string]interface{}) (keys []string) { for k := range m { keys = append(keys, k) } return keys } // use `Keys` func func main() { m := map[string]interface{}{ "foo": 1, "bar": true, "baz":"baz", } fmt.Println(Keys(m)) // [foo bar baz] } |
Is there a way to get a list of all the keys in a Go language map?
1 | ks := reflect.ValueOf(m).MapKeys() |
how do I iterate over all the keys?
使用公认的答案:
1 | for k, _ := range m { ... } |