Junior · Go foundations

Bytes, runes and text

What does len(s) count, and when does range give the wrong index for a UI?

Try explaining this aloud before opening the answer. State your assumptions and trace a boundary case.

EXAMPLE · FRAGMENT UNLESS A COMPLETE PROGRAM IS SHOWN

go
for offset, r := range "Go世" {
    fmt.Println(offset, r)
}
Reveal a strong answer
  1. A Go string is an immutable sequence of bytes. len reports bytes; indexing yields a byte. UTF-8 is common but a string may contain arbitrary bytes.

  2. range decodes UTF-8 and yields byte offsets plus runes. A rune is a Unicode code point, not necessarily a user-perceived character: combining sequences and emoji can contain multiple code points.

  3. Choose semantics first: byte protocols use bytes, code-point operations use runes, and human text cursor movement needs grapheme-aware rules. Converting repeatedly to []rune allocates and loses the original byte-index relationship.

Common trap

“Rune equals character” fails for combining marks and joined emoji.

Try it

For "Go世", give byte length, rune count and the offsets produced by range.

Worked solution

The UTF-8 byte length is 5; there are 3 runes at byte offsets 0, 1 and 2. Use explicit UTF-8 fixtures and invalid-byte cases when testing parsers.

Change the constraint

How do you truncate untrusted UTF-8 without cutting a multi-byte encoding?

How did you do?

Self-assessment, not a compiler pass or interview score. Explain the reasoning unaided before marking understood.

Not marked. Progress stays on this browser, separate from course completion.

Primary references

Checked 2026-10-20. Use documentation for your pinned runtime, driver and tool version.