Go Strings and Runes
In Go, strings are read-only slices of bytes. When we talk about "characters," Go uses a concept called a rune.
What is a Rune?
A rune is an alias for int32. It represents a single Unicode character (code point). Since some characters (like '世' or emojis) take up multiple bytes, a simple index like s[i] might only give you a fraction of a character.
Basic Example
Key Differences
| Feature | String Byte (s[i]) |
Rune (rune) |
|---|---|---|
| Represents | A single byte (8 bits) | A Unicode character (32 bits) |
| Best for | Raw data, ASCII text | International text, Emojis |
String Operations
Go provides a powerful strings package for common tasks:
Important Rule: Immutability
Strings in Go are immutable. You cannot change a character inside a string once it is created.
To modify a string, you must convert it to a slice of runes or bytes, change it, and convert it back: