Go: How to Iterate Over the Keys of a Map

This is kind of embarrassing but I had to go searching in the Go documentation for this. It should have been obvious. I actually know what happened. I spent too much time using languages that have special syntax for all sorts of stuff. That left me thinking that iterating over the keys for a map would require something special. Thankfully in Go it all works the same.

aMap := map[string]string{ "key1":"val1", "key2":"val2", "key3":"val3" } 

for aKey, aVal := range aMap {
    // Do something with aKey and aVal or Go will complain
    fmt.Printf ( "%s maped to %v\n", aKey, aVal )
} 

That's it. You just iterate over it just like an array or anything else.

The example also shows using _ to ignore some values and having an index. A complete example (ex01.go):

package main

// A map/key demo

import (
	"fmt"
)

func main() {

	aMap := map[string]string{"key1": "val1", "key2": "val2", "key3": "val3"}

	fmt.Printf("with both key and value from the range\n")
	for aKey, aVal := range aMap {
		// Do something with aKey and aVal or Go will complain
		fmt.Printf("%s maped to %v\n", aKey, aVal)
	}

	fmt.Printf("\nwith both key the range\n")
	for aKey, _ := range aMap {
		fmt.Printf("%s maped to %v\n", aKey, aMap[aKey])
	}

	// Note: Go has ***no*** defined order for the keys in a map!
	// Sorting the keys is a different topic.
	fmt.Printf("\nwith a position printed out\n")
	i := 0
	for aKey, aVal := range aMap {
		i++
		fmt.Printf("%d: %s maped to %v\n", i, aKey, aVal)
	}

}


and the output (ex01.out):

with both key and value from the range
key1 maped to val1
key2 maped to val2
key3 maped to val3

with both key the range
key1 maped to val1
key2 maped to val2
key3 maped to val3

with a position printed out
1: key1 maped to val1
2: key2 maped to val2
3: key3 maped to val3



•       •       •       •       •       •

Summary: # of Words: 226
Author: Philip J. Schlump
Published On: 2013-12-05

Download code from this articles in .tar.gz for Mac/Linux/Unix or .zip with CR/LF for Windows format.

 

Before You Go....

Have you read "Unintend Consinsequences"?

"I laughed so hard it hurt..."
    Rod Brown

"Incredibly funny! Incredibly true!"
    Tad Stevens