liveBook · Manning

Io.Reader

As explained in Go by Example

io.Reader is a Go interface whose Read method fills a caller-provided byte slice with incoming data and reports the amount read and any error.

io.Reader is a Go interface for streaming incoming data. Its Read method fills a byte slice supplied by the caller and reports how many bytes it read and any error. section 5.2.3

type Reader interface {
    Read(p []byte) (n int, err error)
}

The interface has one method: callers provide the destination buffer, while the Reader reports the transferred byte count and error. section 5.2.3

This caller-managed design avoids allocating a new slice for every read. Reusing a preallocated buffer limits memory use, especially when processing large or size-limited streams. section 5.2.3

Streaming an HTTP response

An HTTP response body is a Reader, so its bytes can be processed incrementally. Reading it with io.ReadAll stores the complete body in memory and may allocate repeatedly; streaming is preferable when only the downloaded size matters. section 7.3.3

Practice the interface by:

  • Satisfying Reader with a type that reads from a []byte. section 7.7
  • Passing that Reader to Copy alongside a Writer that counts bytes. section 7.7

How Go by Example covers it

How deep it goes
Defines the single-method contract, explains caller-managed buffers, and contrasts streaming with io.ReadAll.
Examples
Uses HTTP response bodies, byte-slice readers, counting writers, and Copy exercises.
What it assumes
Assumes familiarity with Go interfaces, byte slices, HTTP responses, and basic Writer usage.
What you can do after
Apply it via io.Copy or incremental reads to process streams without retaining complete responses.
How it connects
Connects io.Reader with io.Writer, io.ReadCloser, io.Closer, io.Copy, and io.ReadAll.

Also explained in

Compare how 3 books explain io.Reader →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go by Example. The section links point to the parts of the book it draws on.