unicode
Before You Start
- Applies to: Go 1.21+ (examples verified with Go 1.22) · Prerequisites: Base: Strings · Read time: about 8 min
In Go language development, string slicing is a high-frequency operation. Special attention needs to be paid to encoding issues, especially when dealing with mixed Chinese and English text. This article systematically organizes four mainstream string slicing methods in Go, analyzing technical points with code examples.
Unicode Safe Processing Method
Achieve character-level safe slicing through []rune conversion:
go
func main() {
str := "Hello, 世界!"
runes := []rune(str)
// Character-level safe slicing
sub3 := string(runes[7:9])
fmt.Println("Safe Chinese slicing:", sub3) // Output: 世界
}Technical Comparison:
| Method | Time Complexity | Memory Overhead | Applicable Scenarios |
|---|---|---|---|
| Byte Slice | O(1) | Low | Pure ASCII strings |
| []rune Conversion | O(n) | High | Strings containing multi-byte characters |
Complete Example
The program below runs as-is: copy it into a file and execute go run main.go, or paste it into the Go Playground.
go
package main
import (
"fmt"
"unicode"
"unicode/utf8"
)
func main() {
r := 'G'
fmt.Println(unicode.IsLetter(r), unicode.IsUpper(r), unicode.ToLower(r))
cn := '中'
fmt.Println(unicode.Is(unicode.Han, cn), utf8.RuneLen(cn))
count := 0
for _, r := range "a1中!" {
if unicode.IsLetter(r) {
count++
}
}
fmt.Println("letters:", count)
}Expected output:
text
true true 103
true 3
letters: 2Common Pitfalls
lenis bytes, not characters. Useutf8.RuneCountInStringfor character counts.- Test categories, not code points.
unicode.Is(unicode.Han, r)is safer than comparing numeric ranges. - Case mapping can expand. Some runes uppercase to multiple characters; length is not preserved.
- Convert to
[]runebefore indexing characters.[]rune(s)[i]gives the i-th character, not byte. utf8validates boundaries.utf8.DecodeRuneInStringis the safe way to step through a string.
Change Log
- 2026-10-14: Added "Before You Start" notes, a complete runnable example with expected output, common pitfalls, and this change log.
