Range over onefont.Graphemes to keep a letter with its combining accent or an emoji sequence together.
go get recursiveai.org/go/onefontpackage main import ( "fmt" "unicode/utf8" "recursiveai.org/go/onefont" ) func main() { text := "e\u0301👨👩👧x" for cluster := range onefont.Graphemes(text) { runes := utf8.RuneCountInString(cluster) fmt.Printf("%s: %d\n", cluster, runes) } }
The number after each cluster is its rune count, not its byte length.
Paste the code above into main.go, run go mod init example and go get recursiveai.org/go/onefont, then go run .; or unzip the example and go run ..
Requires Go 1.24 or later.
é: 2 👨👩👧: 5 x: 1
Variations
Keep byte offsets. Remove the unicode/utf8 import and replace the loop in main:
start := 0 for end := range onefont.GraphemeBreaks(text) { fmt.Printf("%d:%d %s\n", start, end, text[start:end]) start = end }
0:3 é 3:21 👨👩👧 21:22 x
Related recipes
The short answer
Range over onefont.Graphemes(text) to get substrings containing one extended grapheme cluster each. Use onefont.GraphemeBreaks(text) when you need byte offsets into the original string, for example to place a caret or delete the last cluster without leaving part of it behind.
What is the difference between runes and grapheme clusters in Go?
range on a Go string decodes one UTF-8 code point at a time and yields its byte index and rune. That is useful when the code point is the unit you need. For cursor movement or character limits in a text field, it can split what a reader sees as one unit. In the sample, e and U+0301 (combining acute accent) are separate runes. The family emoji is three pictographs joined by two zero-width joiners. Each sequence is one cluster, even though neither is one rune.
A cluster is also not a glyph or a unit of display width. The shape a font draws can depend on its rules and on surrounding text. Count clusters to enforce a text length expressed in perceived characters, not to decide how many clusters fit on a line.
How do I slice a Go string without breaking accents or emoji?
Use the end of a cluster from GraphemeBreaks as the slice boundary. Its first return value for the sample is 3, so text[:3] includes the base letter and the accent. The next boundary is 21; text[3:21] is the complete emoji sequence. Keep the previous offset (starting at zero) if you need both ends. Don’t use a count of clusters as a byte index, and don’t subtract one from an exclusive end: that can leave a partial UTF-8 encoding.
The iterator follows the default extended grapheme cluster rules in Unicode UAX #29. onefont-go v1.1.1 uses Unicode 17.0.0. It does not normalize text: precomposed é and e followed by the combining accent can both be one cluster while remaining different strings. For nonempty input the last boundary is len(text), and there’s no boundary at zero; empty input yields none.