liveBook · Manning

Bytes

As explained in 100 Go Mistakes and How to Avoid Them

A byte is Go's alias for the unsigned 8-bit integer type uint8 and commonly represents one raw byte of data.

A byte is Go’s alias for the unsigned 8-bit integer type uint8. Strings store immutable sequences of bytes, so byte positions are not necessarily character positions. section 5.0 section 5.2

The byte-indexing mistake

For s := "hêllo", ranging over the string visits rune-starting byte indexes: 0, 1, 3, 4, and 5. Printing s[i] prints one byte, producing corrupted output such as Ã, while len(s) returns 6 bytes rather than 5 runes. section 5.2

Choose the representation that matches the operation:

  • Use the range value, for i, r := range s, when iterating over decoded runes; i is the starting byte index and r is the rune. section 5.2
  • Convert with []rune(s) when you need rune indexes or direct rune-slice access; use []byte when operating on raw bytes. section 5.2 section 5.0
  • Use utf8.RuneCountInString for rune counts only when the string is treated as UTF-8; strings can also contain arbitrary bytes. section 5.1 section 5.2
s := "hêllo"            #1
for i := range s {
    fmt.Printf("position %d: %c\n", i, s[i])
}
fmt.Printf("len=%d\n", len(s))

Inspect the failing loop and its concrete output to see how byte indexes diverge from rune positions. section 5.2

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Explains byte storage and UTF-8 indexing through runnable output, then stops short of broader byte-level APIs.
Examples
Uses ĥ-free hês? No: uses "hêllo", byte indexes, corrupted à output, rune slices, and UTF-8 rune counting.
What it assumes
Assumes basic strings and loops, then builds the distinction between character sets, encodings, code points, bytes, and runes.
What you can do after
Diagnose string iteration bugs by distinguishing byte indexes, byte values, rune values, and rune counts.
How it connects
Connects bytes with strings, runes, Unicode, UTF-8 encoding, string iteration, and rune counting.

Also explained in

Compare how 7 books explain bytes →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.