Skip to main content

Readers and Writers

Intro

As programmers, we mostly pass information around. This information is just a bunch of bytes. For a computer it doesn't really matter if you're dealing with a string, a text file or a picture: they are just bytes.

This bunch of bytes is translated in Go as a slice of bytes:

// this can hold some information containing 7 bytes
information := make([]byte, 7)

So before diving into I/O in Go, we should know that what we really are dealing with is passing slices of bytes around: eiter as input or output.

The fundamental interfaces used in our passing of information are the io.Reader and io.Writer.

io.Reader

The io.Reader interface represents a piece of information that can be read from.

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

io.Writer

The io.Writer interface represents a piece of information that can be written to.

type Writer interface {
Write(p []byte) (n int, err error)
}

Just to clear out any confusion: a Writer is not something that writes, but something to which you can write into. A Reader is not something that reads, but something you can read from.

A file is a very good example being both a Reader and a Writer. You can read a file and you can also write to a file.