Essential Go edit forum

range statement

Iterate over a string

s := "Hey 世界"
for i, r := range s {
	fmt.Printf("idx: %d, rune: %d\n", i, r)
}

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)
}

Iterate over a slice

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

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

  ↑ ↓ to navigate     ↵ to select     Esc to close