Skip to content

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: ​

MethodTime ComplexityMemory OverheadApplicable Scenarios
Byte SliceO(1)LowPure ASCII strings
[]rune ConversionO(n)HighStrings 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: 2

Common Pitfalls ​

  • len is bytes, not characters. Use utf8.RuneCountInString for 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 []rune before indexing characters. []rune(s)[i] gives the i-th character, not byte.
  • utf8 validates boundaries. utf8.DecodeRuneInString is 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.

Golang by www.golangdev.cn · Adapted in part from Golang 中文学习文档 (MIT, © 寒江蓑笠翁)