Go edit

range statement

Iterate over a string

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

Notice that range assumes that string is UTF-8 encoded and iterates over Unicode characters (runes), not bytes of the string.

First returned value i is byte index of the rune in the string, not Unicode character index.

To iterate over characters, use byte indexes:

s := "a 世"
for i := 0; i < len(s); i++ {
	c := s[i]
	fmt.Printf("idx: %d, byte: %d\n", i, c)
}
idx: 0, byte: 97
idx: 1, byte: 32
idx: 2, byte: 228
idx: 3, byte: 184
idx: 4, byte: 150

Iterate over a slice

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

Iterate 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: five, value: 5
key: three, value: 3

Feedback about page:

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

  ↑ ↓ to navigate     ↵ to select     Esc to close