IO with readers and writers
Similar to other languages, such as Java, Go models data input and output as a stream that flows from sources to targets. Data resources, such as files, networked connections, or even some in-memory objects, can be modeled as streams of bytes from which data can be read or written to, as illustrated in the following figure:
The stream of data is represented as a slice of bytes ([]byte) that can be accessed for reading or writing. As we will explore in this chapter, the
io
package makes available the io.Reader
interface to implement code that reads and transfers data from a source into a stream of bytes. Conversely, the io.Writer
interface lets implementers create code that reads data from a provided stream of bytes and writes it as output to a target resource. Both interfaces are used extensively in Go as a standard idiom to express IO operations. This makes it possible to interchange readers and writers of different implementations and contexts with predictable...