Input and Output Operations
A common operation in a program is to move data around and to reformat it. For example, you can open a file, load its content in memory, encode it to a different format, maybe jpeg, and then write it to a file on the disk. This is where the io.Reader
and io.Writer
interfaces play a key role in Go's I/O model, as they allow you to stream data from a source to a destination via a transfer buffer. This means you don't need to load the entire file in memory to encode it and write it to the destination, making the process more efficient.
The io.Reader Interface
The io package in the standard library defines one of the most popular interfaces in Go, the io.Reader
interface, which can read a stream of bytes (p
). It returns the number of bytes read (n
) and any error encountered (err
).
type Reader interface {
Read(p []byte) (n int, err error)
}
Any concrete type that has a method Read
with this signature implements the io.Reader
interface. You don&...