Iterate a map with range

suggest change

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents