开发者

Iterating over all the keys of a map

开发者 https://www.devze.com 2022-12-13 00:18 出处:网络
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:

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 al开发者_Go百科l the keys?


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

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

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.


Here's some easy way to get slice of the map-keys.

// 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?

ks := reflect.ValueOf(m).MapKeys()

how do I iterate over all the keys?

Use the accepted answer:

for _, k := range m { ... }


A Type agnostic solution:

for _, key := range reflect.ValueOf(yourMap).MapKeys() {
    value := yourMap.MapIndex(key).Interface()
    fmt.Println("Key:", key, "Value:", value)
}  


Using Generics:

func Keys[K comparable, V any](m map[K]V) []K {
    keys := make([]K, 0, len(m))

    for k := range m {
        keys = append(keys, k)
    }

    return keys
}


For sorted keys of map[string]string.

package main

import (
    "fmt"
    "sort"
)

func main() {
    m := map[string]string{"key1": "val1", "key2": "val2"}
    sortStringMap(m)
}

// sortStringMap prints the [string]string as keys sorted
func sortStringMap(m map[string]string) {
    var keys []string
    for key := range m {
        keys = append(keys, key)
    }
    sort.Strings(keys)  // sort the keys
    for _, key := range keys {
        fmt.Printf("%s\t:%s\n", key, m[key])
    }
}

output:

key1    :val1
key2    :val2

0

精彩评论

暂无评论...
验证码 换一张
取 消