Essential Go  Edit on GitHub      File Issue

range statement

Basics of range.

Iterate over a string:

s := "Hey 世界"
for idx, rune := range s {
	fmt.Printf("idx: %d, rune: %d\n", idx, rune)
}
idx: 0, rune: 72
idx: 1, rune: 101
idx: 2, rune: 121
idx: 3, rune: 32
idx: 4, rune: 19990
idx: 7, rune: 30028

Iterate over a slice:

a := []int{3, 15, 8}
for idx, el := range a {
	fmt.Printf("idx: %d, element: %d\n", idx, el)
}
idx: 0, element: 3
idx: 1, element: 15
idx: 2, element: 8

Iterage over a map:

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
  ↑ ↓ to navigate     ↵ to select     Esc to close