Strings, Bytes, and Runes in Go: Why len() Counts Bytes
See why len() counts UTF-8 bytes instead of characters, iterate safely over runes with range, and slice UTF-8 text without splitting multi-byte characters. After this, accented text and emoji will not break your string indexing.
Skip ahead
Already know len(s) counts bytes, not characters? Jump to Case 2: why slicing s[:4] corrupts UTF-8 or Case 4: when to use []byte vs. string vs. []rune.
In Python, len("café") returns 4 and "café"[:3] returns "caf". In Go, len("café") returns 5, and slicing "café"[:4] produces corrupted invalid UTF-8 ("caf\xc3")! That single surprise causes broken username truncation, garbled CSV exports, and wrong character-limit validation in APIs serving international text.
Once you understand Go's three text types—string (immutable UTF-8 bytes), byte (uint8), and rune (int32 Unicode code point)—international text behaves predictably every time. Verified on Go 1.27.
Case 1: len(s) counts bytes; utf8.RuneCountInString counts runes
In UTF-8, ASCII characters take 1 byte, accented Latin characters like 'é' take 2 bytes (0xC3 0xA9), CJK characters take 3 bytes, and emojis take 4 bytes. Because Go strings are plain read-only slices of bytes, len(s) runs in O(1) time by returning the byte count—not the character count:
package main
import (
"fmt"
"unicode/utf8"
)
func main() {
s := "café"
fmt.Printf("len(bytes)=%d runes=%d\n", len(s), utf8.RuneCountInString(s))
fmt.Printf("bad slice s[:4]=%q\n", s[:4])
runes := []rune(s)
fmt.Printf("safe rune slice=%q\n", string(runes[:3]))
for i, r := range s {
fmt.Printf("byte=%d rune=%q (%U)\n", i, r, r)
}
}
len(bytes)=5 runes=4
bad slice s[:4]="caf\xc3"
safe rune slice="caf"
byte=0 rune='c' (U+0063)
byte=1 rune='a' (U+0061)
byte=2 rune='f' (U+0066)
byte=3 rune='é' (U+00E9)
Case 2: Why slicing s[:4] broke "café" in half
Look closely at the byte offsets printed by for i, r := range s: 'c' sits at byte 0, 'a' at 1, 'f' at 2, and 'é' spans bytes 3 and 4! Writing s[:4] sliced right through the middle of 'é', leaving an orphaned leading byte 0xC3 (which browsers and terminals render as the broken replacement diamond ).
To truncate a string safely to N characters (for example a 140-character preview or username limit), convert to []rune(s) first—or walk rune boundaries with for i := range s so you never split a multi-byte character.
Case 3: Indexing s[i] vs. for _, r := range s
Watch the difference between the two loops:
for i := 0; i < len(s); i++: Visits raw bytes (s[i]has typebyte/uint8). Fast for pure ASCII delimiters like','or'\n', broken for non-ASCII characters.for i, r := range s: Automatically decodes UTF-8 runes (rhas typerune/int32) and setsito the starting byte offset of each rune (noticeijumped by 2 after a 2-byte rune).
Case 4: Choosing between string, []byte, and []rune
| Type | What it holds | Best used for |
|---|---|---|
string |
Immutable UTF-8 byte sequence | Map keys, config values, struct fields, safe concurrent sharing |
[]byte |
Mutable byte slice | I/O streams, JSON/HTTP buffers, building/modifying text with bytes.Buffer |
[]rune |
Mutable Unicode code points (4 bytes each) | Character-based truncation, reversing text, counting Unicode letters |
💡 Tip
Building strings inside a loop with s += part copies the entire immutable string on every pass. Use var b strings.Builder (and b.Grow(...) when you know the rough size) to assemble strings in O(n) time.
Common mistakes
- Validating max character length with
len(name) > 20: Rejects valid 10-character Japanese or accented names whose UTF-8 byte length exceeds 20. Useutf8.RuneCountInString(name)for character limits, andlen(name)only for byte/storage limits. - Converting
string(65)expecting"65": Converts integer 65 to the Unicode rune'A'! Usestrconv.Itoa(65)to format numbers as decimal strings. - Re-converting
[]byte(s)inside a tight loop: Each conversion allocates a fresh copy; reusestringspackage helpers (strings.Cut,strings.HasPrefix) directly onstringinstead.
⚠ Warning
Never truncate arbitrary user text by byte index (bio[:100]) before saving to a database or JSON response—splitting a multi-byte UTF-8 character produces invalid UTF-8 that PostgreSQL rejects with invalid byte sequence for encoding "UTF8"!
What happens if you skip this
English-only tests pass cleanly, and then the very first accented name, emoji, or non-Latin product title gets silently garbled—or triggers database UTF-8 errors—when sliced by byte offset.
Related course: Go for Beginners.
About
See why len() counts UTF-8 bytes instead of characters, iterate safely over runes with range, and slice UTF-8 text without splitting multi-byte characters. After this, accented text and emoji will not break your string indexing.
- Responsible
- Jay P
- Last Update
- 11/27/2026
- Reading Time
- 4 min
Reviews
Sign in to write a reviewComments
Sign in to commentNo comments yet.