Go Reference ยท Errors, I/O and Files
Go bufio.Reader and bufio.Writer types
Reference for Go bufio.Reader and bufio.Writer: ReadString, ReadLine, Peek, ReadRune, WriteString, Flush, buffer sizes and the common forgotten-Flush bug.
bufio.Reader and bufio.Writer wrap an io.Reader or io.Writer with an in-memory buffer. Every call to a raw file or network connection is a system call; a buffered wrapper collects many small reads or writes into one large operation, which is much faster. The wrappers also add convenient methods such as ReadString, Peek and WriteString.
A Writer holds your output until the buffer is full or you call Flush. Forgetting Flush is the classic bug: the program ends and the last part of the output is silently lost.
r := bufio.NewReader(os.Stdin) w := bufio.NewWriter(os.Stdout) defer w.Flush()
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Syntax
func NewReader(rd io.Reader) *Reader func NewReaderSize(rd io.Reader, size int) *Reader func NewWriter(w io.Writer) *Writer func NewWriterSize(w io.Writer, size int) *Writer func NewReadWriter(r *Reader, w *Writer) *ReadWriter
Main Reader methods:
| Method | Description |
|---|---|
Read(p []byte) (int, error) |
Reads up to len(p) bytes; implements io.Reader. |
ReadString(delim byte) (string, error) |
Reads through the first delim, which is included in the result. |
ReadBytes(delim byte) ([]byte, error) |
Same, but returns a fresh slice. |
ReadLine() (line []byte, isPrefix bool, err error) |
Low-level line reader; most code should use Scanner or ReadString. |
ReadRune() (r rune, size int, err error) |
Reads one UTF-8 character. UnreadRune undoes it. |
ReadByte() / UnreadByte() |
Single bytes. |
Peek(n int) ([]byte, error) |
Next n bytes without consuming them. |
Discard(n int) (int, error) |
Skips n bytes. |
Buffered() int |
Bytes already in the buffer. |
Reset(r io.Reader) |
Reuses the reader for a new source. |
Main Writer methods: Write, WriteString, WriteByte, WriteRune, Flush, Buffered, Available, Size, Reset, and ReadFrom (used by io.Copy).
Errors and edge cases:
ReadStringandReadBytesreturn the data read plusio.EOFwhen the input ends without the delimiter. Always process the data before checking the error.Peekreturnsbufio.ErrBufferFullifnexceeds the buffer size.- Once a
Writerhits a write error, every later call returns that same error;Flushreports it. - The default buffer size is 4096 bytes. The minimum accepted size is 16.
Usage notes
- Always flush. Use
defer w.Flush()right after creating the writer, but note thatos.Exitandlog.Fatalskip deferred calls. - Check the error from
Flush. The final write to disk may fail only when the buffer is flushed. - Lines of any length:
ReadStringhas no line limit, unlikebufio.Scanner, whose default token limit is 64 KiB. UseReadString(or give the scanner a bigger buffer) for huge lines. - Do not mix a
Readerwith direct reads from the underlying source: the reader may already have consumed bytes into its buffer. ReadBytesandReadStringallocate. Inside hot loops preferScannerorReadSlice, whose result is only valid until the next read.Reader.Peekis handy for sniffing a format (%PDF, a gzip header, a BOM) before choosing a parser.- Wrapping something that is already buffered (
bytes.Buffer,strings.Reader) adds cost, not speed. - Printing many lines to the terminal is far faster through a
bufio.Writerthan through repeatedfmt.Println, which writes unbuffered.