Essential Go Basic types  Edit on GitHub      File Issue

Characters and runes

Go has 2 types of characters:

Zero value of a byte and rune is 0.

Iterate over string using bytes

s := "str"
for i := 0; i < len(s); i++ {
	c := s[i]
	fmt.Printf("Byte at index %d is %c (0x%x)\n", i, c, c)
Byte at index 0 is s (0x73)
Byte at index 1 is t (0x74)
Byte at index 2 is r (0x72)

Iterate over string using runes

s := "日本語"
for i, runeChar := range s {
	fmt.Printf("Rune at byte position %d is %#U\n", i, runeChar)
Rune at byte position 0 is U+65E5 '日'
Rune at byte position 3 is U+672C '本'
Rune at byte position 6 is U+8A9E '語'

Note: When iterating over runes, the index will be the offset within the string where the rune begins, rather than the index of the rune itself.

  ↑ ↓ to navigate     ↵ to select     Esc to close