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.
Code
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
ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.ASCII85 EncoderEncode and decode ASCII85 (Base85), the Adobe variant with z zero-compression, handling arbitrary bytes and Unicode.Base32 Encoder & DecoderEncode and decode RFC 4648 Base32 with padding, fully UTF-8 safe so Unicode text round-trips without corruption. Nothing leaves your browser.Base45 Encoder and DecoderEncode and decode text with the Base45 alphabet defined in RFC 9285, with UTF-8 support, padding-free output, and clear validation errors.
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)=`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.