range over a map

suggest change

Iteration over a map has undefined order. In fact, Go compiler goes to the trouble of randomizing the order so that programmers don't rely on accidental order.

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

Feedback about page:

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



Table Of Contents