Essential Go Maps  Suggest an edit

Iterate over a map with range

Iteration order is not specified. Go randomizes the order of iteration on purpose so that code doesn’t incorrectly rely on specific order.

Iterate both keys and values

people := map[string]int{
	"john": 30,
	"jane": 29,
	"mark": 11,
}

for key, value := range people {
	fmt.Printf("key: %s, value: %d\n", key, value)
}
key: john, value: 30
key: jane, value: 29
key: mark, value: 11

Iterate just keys

people := map[string]int{
	"john": 30,
	"jane": 29,
	"mark": 11,
}

for key := range people {
	fmt.Printf("key: %s\n", key)
}
key: john
key: jane
key: mark

Iterate just values

people := map[string]int{
	"john": 30,
	"jane": 29,
	"mark": 11,
}

for _, value := range people {
	fmt.Printf("value: %d\n", value)
}
value: 30
value: 29
value: 11

  ↑ ↓ to navigate     ↵ to select     Esc to close