Read Runes With ReadRune And UnreadRune

Read one rune at a time with bufio.Reader.ReadRune, which reports the byte width, then step back with UnreadRune to re-dispatch a character.

GoData Integrity

Code

gosnippet
32 lines
package main

import (
	"bufio"
	"fmt"
	"io"
	"strings"
)

func main() {
	r := bufio.NewReader(strings.NewReader("go 语言 ✓ 42"))

	// ReadRune 一次消费一个 rune,并报告它占用的字节数
	for i := 0; i < 4; i++ {
		ch, size, err := r.ReadRune()
		if err == io.EOF {
			fmt.Println("eof after", i, "runes")
			break
		}
		if err != nil {
			panic(err)
		}
		fmt.Printf("rune %q bytes %d buffered %d\n", ch, size, r.Buffered())
	}

	// UnreadRune 回退一个 rune:必须紧跟在一次成功的 ReadRune 之后
	if err := r.UnreadRune(); err != nil {
		panic(err)
	}
	ch, size, err := r.ReadRune()
	fmt.Printf("re-read %q bytes %d err %v\n", ch, size, err)
}

The mechanics

Read Runes With ReadRune And UnreadRune comes down to the function main.

A single loop drives the file — for i := 0; i < 4; i++. Only io.EOF is treated as a normal outcome; any other read error, and the UnreadRune guard after the loop, panic immediately since this demo has no recovery to offer.

What to watch for

  • No external packages — everything relies on the language’s built-in APIs.
  • panic(err) appears twice, for the two errors that would mean a broken reader state: a non-EOF read failure mid-loop and an UnreadRune call that follows anything other than a successful ReadRune.

Using it

Signature: func main()

The loop consumes 4 runes before its i < 4 cap ends it, so the io.EOF branch stays unexercised with this 10-rune input — it is the guard for shorter reads, not part of this run’s output. Each rune line reports the rune, its byte width, and how much remains buffered; re-read then prints the same rune UnreadRune stepped back to.

Key statements

if err != nil {
panic(err)
}

Interactive Tools for This Topic

FAQ

What is the error handling style?
The failure path is `panic(err)` — detected problems halt the run rather than being passed back.
What does Read Runes With ReadRune And UnreadRune print when run?
Running the file directly is enough — expect labeled output lines such as `eof after`, `rune`, `re-read`.