Skip to content
Tutorials Center
My learning

Topics

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.

Go
s := "héllo"
len(s)                   // 6 bytes
utf8.RuneCountInString(s) // 5 runes

Try it

Go Bytes versus runes

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.

Go Reversing text and building strings

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 []byte or []rune, modify, and convert back, or use strings.Builder.
  • Literals: interpreted "..." with escapes (\n, é, \xff for a raw byte) and raw `...` without escapes, which may span lines.
  • for i, r := range s decodes UTF-8; the index i advances by the rune size. Invalid UTF-8 yields utf8.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 with s and does not copy. The reverse also holds: a tiny substring keeps a huge original string alive. Use strings.Clone (Go 1.18) to detach.
  • Counting characters: utf8.RuneCountInString counts 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.ToUpper handles Unicode case mapping, but equality is byte-wise. "é" as one rune and "e"+U+0301 are different strings; normalize with golang.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.Builder or strings.Join.
  • []byte and string conversions copy; use the bytes package to avoid converting back and forth.