Understand the contract
A rune represents a Unicode code point and is an alias for int32. A UTF-8 code point may occupy more than one byte, so len(text) and utf8.RuneCountInString(text) can differ. Neither measure necessarily equals the number of visible characters perceived by a reader.
range over a string decodes successive UTF-8 runes. Its index is the byte offset of each rune, not its ordinal position. Converting a string to []rune makes code-point indexing possible, but it allocates a new sequence and still does not segment grapheme clusters.
Work through the example
The example uses a precomposed accented letter. "Go, sí" contains six runes and seven UTF-8 bytes. The printed offsets show where the two-byte í begins. Printf with %c prints a rune as a character, while %U can show its Unicode code-point notation.
package main
import (
"fmt"
"unicode/utf8"
)
func main() {
text := "Go, sí"
fmt.Println(len(text), utf8.RuneCountInString(text))
for offset, r := range text {
fmt.Printf("%d %c\n", offset, r)
}
}Watch this boundary
Visually identical text can use different sequences of code points, such as an accented letter versus a base letter plus a combining accent. A rune-based length check alone may give different results for those inputs. Document whether your rule limits storage bytes, code points or displayed grapheme clusters.
Practice with a changed input
Compare "é" with "é" using byte and rune counts. Then use utf8.ValidString to check a string containing an invalid UTF-8 byte.
Lesson 18 of 50
View the full Go basics seriesReferences & further reading
Need help with your Go backend?
I work with engineering teams on focused Go and Kubernetes platform engagements, with limited consulting availability.
Explore Go consulting services