Runes and String Encoding

In Go, strings are sequences of bytes encoded in UTF-8. This allows Go to natively support a wide variety of characters, including emojis and non-English scripts.

Bytes vs. Runes

  • byte: An alias for uint8. It represents 8 bits of data. A single character (like ‘A’) might be 1 byte, but more complex characters (like 🐻) can take up 4 bytes.
  • rune: An alias for int32. It represents a single Unicode code point. Regardless of how many bytes a character takes to store, it is exactly one rune.

Working with Characters

When you need to iterate over characters in a string or handle individual symbols, you should use the rune type to ensure you don’t break up a multi-byte character.

const emoji = "🐻"
fmt.Println(len(emoji))                    // 4 (bytes)
fmt.Println(utf8.RuneCountInString(emoji)) // 1 (rune)

Key Takeaway

Go strings can hold arbitrary data, but by default, they are treated as UTF-8 encoded text. Using rune allows you to handle each character correctly regardless of its encoded size.