liveBook · Manning

Io.Reader

As explained in Go in Action, Second Edition

io.Reader is the Go interface for reading a stream of bytes into a supplied buffer.

io.Reader is Go’s interface for reading bytes into a supplied buffer. Accepting a reader lets processing code work with files, standard input, memory buffers, or network connections without depending on a particular source type. section 2.8.2 section 10.3

The interface has one method: Read(p []byte) (n int, err error). It reads up to len(p) bytes, returning the number read and any error encountered. A short read may return available data rather than wait for the buffer to fill; Read may also use the entire buffer as scratch space during the call. section 2.8.2

Listing 2.40 Excerpt from go doc io.Reader
type Reader interface {
        Read(p []byte) (n int, err error)
}
    Reader is the interface that wraps the basic Read method.

    Read reads up to len(p) bytes into p. It returns the number of bytes
    read (0 <= n <= len(p)) and any error encountered. Even if Read returns
    n < len(p), it may use all of p as scratch space during the call. If
    some data is available but not len(p) bytes, Read conventionally returns
    what is available instead of waiting for more.

The interface definition and Read contract show exactly what an implementation must provide. section 2.8.2

A type satisfies io.Reader by providing the required Read method. For example, os.Open returns an *os.File, whose Read method makes it usable wherever a reader is accepted. The interface describes what a consumer can do with the value, not how the underlying source is implemented. section 2.8.2

Scan standard input

Pass os.Stdin to bufio.NewScanner, call Scan in a loop, and use Text to retrieve each token. After the loop, check Err for a scanning error. The same scanner constructor can accept another io.Reader, such as an opened file. section 2.8.1 section 2.8.2

For input-to-output processing, a function can accept an io.Reader and an io.Writer independently. Related interfaces compose capabilities: io.ReadCloser adds closing behavior, while io.MultiReader combines readers into a sequential stream. section 10.3

How Go in Action, Second Edition covers it

How deep it goes
Defines the Read signature and buffer behavior, then explains interface satisfaction and composition with other I/O capabilities.
Examples
Uses a standard-input scanner, an opened file, and a JSON/XML validation and conversion utility.
What you can do after
Apply it via bufio.Scanner or a processing function to accept interchangeable input sources.
How it connects
Connects Go interfaces with bufio.Scanner, io.Writer, io.Closer, io.ReadCloser, and io.MultiReader.

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 in Action, Second Edition. The section links point to the parts of the book it draws on.