Golang bufio.UnreadRune() function example

package bufio

UnreadRune unreads the last rune. If the most recent read operation on the buffer was not a ReadRune, UnreadRune returns an error. (In this regard it is stricter than UnreadByte, which will unread the last byte from any read operation.)

Golang bufio.UnreadRune() function usage example

 utf8buf := []byte("世界")
 readbuffer := bytes.NewBuffer(utf8buf)
 reader := bufio.NewReader(readbuffer)

 fmt.Println(reader.UnreadRune()) // this will cause error, because there is nothing to "unread"
 rune, _, _ := reader.ReadRune()  // read first rune which is 世

 fmt.Println(string(rune)) // prints 世

 rune, _, _ = reader.ReadRune() // read the next rune, which is 界

 fmt.Println(string(rune)) // prints 界

 fmt.Println(reader.UnreadRune()) // this will NOT cause error, because reader managed to "unread"

Output :

bufio: invalid use of UnreadRune

Reference :

http://golang.org/pkg/bufio/#Reader.UnreadRune

Advertisement