← 中文资源

简体中文版本

DecodeRune 手工解码 UTF-8 字节

utf8.DecodeRune 按序列消费字节并返回宽度,坏字节以 RuneError+宽度 1 浮出而不卡流;EncodeRune 与 RuneLen 是配套的编码与测长。

阅读英文原文

实现说明

DecodeRune 手工解码 UTF-8 字节可以归结为函数 main。 驱动整个流程的是 for pos < len(text) 这一个循环。

使用要点

  • 演示输出是带标签的(pos、encoded、len(a)=),每个操作都会留下自己的一行标注。

常见问题

运行「DecodeRune 手工解码 UTF-8 字节」会打印什么?

文件本身就是完整程序,直接运行——输出行带有 pos、encoded、len(a)= 这类标签。

核心语句

buf := make([]byte, utf8.UTFMax)
pos += width

代码示例

package main

import (
	"fmt"
	"unicode/utf8"
)

func main() {
	text := []byte("aé世")

	// DecodeRune:每次消费一个 UTF-8 序列,返回 (rune, 宽度)
	pos := 0
	for pos < len(text) {
		r, width := utf8.DecodeRune(text[pos:])
		fmt.Printf("pos %d: %q width %d\n", pos, r, width)
		pos += width
	}

	// EncodeRune 是逆操作:把 rune 编码回字节并返回写入宽度
	buf := make([]byte, utf8.UTFMax)
	n := utf8.EncodeRune(buf, '世')
	fmt.Printf("encoded %d bytes: % x\n", n, buf[:n])

	// RuneLen 给出编码长度,不必真的编码
	fmt.Println("len(a)=", utf8.RuneLen('a'), "len(世)=", utf8.RuneLen('世'))

	// 非法字节:DecodeRune 返回 RuneError 且宽度为 1,流不卡死
	bad := []byte{0xff, 'z'}
	r, width := utf8.DecodeRune(bad)
	fmt.Printf("bad: rune=%q width=%d\n", r, width)
}