Iterating over all the keys of a map

LoopsDictionaryGo

Loops Problem Overview


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?

Loops Solutions


Solution 1 - Loops

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.

Solution 2 - Loops

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]
}

Solution 3 - Loops

> 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 { ... }

Solution 4 - Loops

A Type agnostic solution:

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

Solution 5 - Loops

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
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMartin RedmondView Question on Stackoverflow
Solution 1 - LoopsJonathan FeinbergView Answer on Stackoverflow
Solution 2 - Loopsa8mView Answer on Stackoverflow
Solution 3 - LoopsSridharView Answer on Stackoverflow
Solution 4 - LoopsMohsenView Answer on Stackoverflow
Solution 5 - LoopsfliXView Answer on Stackoverflow