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

main.go

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

Output:

key: three, value: 3
key: five, value: 5

Get only key

main.go

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

Output:

key: three
key: five

Get only value

main.go

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

Output:

value: 3
value: 5

Feedback about page:

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



Table Of Contents