Essential Go range statement  Edit on GitHub      File Issue

range over a map

There are 3 variants of iterating over a map with range.

Get both key and value:

m := map[string]int{
	"three": 3,
	"five":  5,
}
for key, value := range m {
	fmt.Printf("key: %s, value: %d\n", key, value)
}
key: three, value: 3
key: five, value: 5

Get only key:

m := map[string]int{
	"three": 3,
	"five":  5,
}
for key := range m {
	fmt.Printf("key: %s\n", key)
}
key: three
key: five

Get only value:

m := map[string]int{
	"three": 3,
	"five":  5,
}
for _, value := range m {
	fmt.Printf("value: %d\n", value)
}
value: 3
value: 5
  ↑ ↓ to navigate     ↵ to select     Esc to close