Go Reference · Concepts
Strings, bytes and runes in Go
How Go strings store UTF-8, the difference between bytes, runes and characters, how range and len behave, and how to slice, count and reverse text correctly.
A Go string is an immutable sequence of bytes. By convention, and in all string literals in source code, those bytes are UTF-8 encoded text. A rune (alias for int32) holds one Unicode code point. A byte (alias for uint8) holds one byte. A user-perceived "character" can be several runes, such as a letter followed by a combining accent.
This matters because len(s) counts bytes, s[i] yields a byte, and slicing cuts at byte positions. Only for range over a string and the unicode/utf8 package see runes.
s := "héllo" len(s) // 6 bytes utf8.RuneCountInString(s) // 5 runes
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input · what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input · what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Usage notes
- Strings are read-only.
s[0] = 'x'does not compile. Convert to[]byteor[]rune, modify, and convert back, or usestrings.Builder. - Literals: interpreted
"..."with escapes (\n,é,\xfffor a raw byte) and raw`...`without escapes, which may span lines. for i, r := range sdecodes UTF-8; the indexiadvances by the rune size. Invalid UTF-8 yieldsutf8.RuneError(U+FFFD) with width 1.for i := 0; i < len(s); i++walks bytes, which is right for ASCII protocols and wrong for general text.- Slicing is cheap:
s[a:b]shares memory withsand does not copy. The reverse also holds: a tiny substring keeps a huge original string alive. Usestrings.Clone(Go 1.18) to detach. - Counting characters:
utf8.RuneCountInStringcounts code points, not grapheme clusters. For user-visible characters (emoji with modifiers, combined accents) you need a segmentation library, since the standard library has none. - Case and normalization:
strings.ToUpperhandles Unicode case mapping, but equality is byte-wise."é"as one rune and"e"+U+0301are different strings; normalize withgolang.org/x/text/unicode/norm. - Comparison and sorting are by bytes, which for UTF-8 equals code point order, but not alphabetical order in any language.
- Concatenation in loops is quadratic. Use
strings.Builderorstrings.Join. []byteandstringconversions copy; use thebytespackage to avoid converting back and forth.