Land your first dev job — 100% money-back guarantee.
Continue

Readers, Writers and Buffers in Go

Learn the `io.Reader` and `io.Writer` interfaces, `bytes.Buffer`, `io.Copy`, and buffered I/O with `bufio`.

io.Reader and io.Writer

`io.Reader` is anything that can read bytes into a slice: `Read(p []byte) (n int, err error)`. `io.Writer` is anything that can accept bytes: `Write(p []byte) (n int, err error)`. Many types implement these interfaces: files, network connections, in-memory buffers, and HTTP bodies. Code that accepts `io.Reader` or `io.Writer` can work with any implementation.

1. Reading from a strings.Reader

Treat a string as a stream of bytes.

2. Writing to os.Stdout

os.Stdout implements io.Writer.

bytes.Buffer

`bytes.Buffer` holds a slice of bytes that grows as needed. It implements `io.Reader`, `io.Writer`, `io.ByteReader`, and more, so you can build strings or binary data in memory and then read them back without extra copies.

1. Write and Read with bytes.Buffer

Accumulate bytes then consume as a reader.

io.Copy

`io.Copy(dst, src)` copies from `src` (`io.Reader`) to `dst` (`io.Writer`) until EOF or an error. It uses an internal buffer so you do not need to allocate a large slice yourself.

1. Copy Between Reader and Writer

Stream data without loading all at once.

Buffered I/O with bufio

The `bufio` package wraps an `io.Reader` or `io.Writer` with an in-memory buffer. That reduces syscalls when reading files or sockets and provides helpers like `ReadString`, `ReadLine`, and `Scanner` for convenient line-by-line input.

1. bufio.Scanner for Lines

Read input line by line.

2. bufio.Writer

Buffer writes before flushing.