DecodeRune Reads Bytes Into Runes

Walk a byte slice with utf8.DecodeRune, which consumes one UTF-8 sequence per call and reports its width so malformed bytes surface as RuneError.

GoData Integrity

Code

gosnippet
31 lines
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)
}

Inside the snippet

DecodeRune Reads Bytes Into Runes keeps everything in the function main.

Iteration happens inside for pos < len(text) — everything outside it runs once.

What to watch for

  • Nothing third-party is pulled in; the snippet is dependency-free.

Putting it to use

Output lines are prefixed (pos, encoded, len(a)=), so the effect of each step stands out plainly.

The core lines, annotated

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

Interactive Tools for This Topic

FAQ

What does DecodeRune Reads Bytes Into Runes print when run?
Run it as a complete program — the output lines carry labels such as `pos`, `encoded`, `len(a)=`.