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.
Code
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
CSV to TSV ConverterParse RFC 4180 CSV with quoted fields and re-serialize using a tab, pipe, semicolon, or custom delimiter, with optional quoting.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does Bufio ReadString Keeps Delimiter print when run?
- The script runs standalone; its 2 labeled outputs include `first=`, `tail=`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.