Bufio ReadString Keeps Delimiter

Read newline-framed input with bufio.Reader.ReadString, which returns the delimiter attached and reports io.EOF when the stream ends mid-line.

GoData Integrity

Code

gosnippet
19 lines
package main

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

func main() {
	reader := bufio.NewReader(strings.NewReader("one\ntwo"))

	// ReadString 保留分隔符(keeps the delimiter):读到的行自带 \n
	line, err := reader.ReadString('\n')
	fmt.Printf("first=%q err=%v\n", line, err)

	// 流末尾没有分隔符:剩余内容照常返回,err 才是 io.EOF
	tail, err := reader.ReadString('\n')
	fmt.Printf("tail=%q err=%v\n", tail, err)
}

A closer look

Everything happens inside the function main.

What to watch for

  • Runs on the standard library alone; nothing to install.

Using it

The signature doing the work here: func main()

The demo output is labeled (first=, tail=); each label names the call that printed it.

Key statements

reader := bufio.NewReader(strings.NewReader("one\ntwo"))

Interactive Tools for This Topic

FAQ

What does Bufio ReadString Keeps Delimiter print when run?
The script runs standalone; its 2 labeled outputs include `first=`, `tail=`.