The Writer Interface
Writing bytes in various places is an extremely common use case in all computer programs.
- writing JSON to an HTTP output
- ones and zeros to a network router
- bits into a digital port to turn a light on
- encoded pixels to a printer
- or letters on a console
Go has a set of standard interfaces for the most common uses, such as writing or reading bytes.
This means that everyone who produces code that writes or reads bytes can use these existing interfaces.
Pithy
You should always try to use the
io.Writerinterface in your code to make it more modular it allows users to swap in whatever type they want and have it write there instead.
The most common:
io.Writerto write to any destinationio.Readerto read from any source
// How to see what required to meet an interface
go doc io.Writer
type Writer interface {
Write(p []byte) (n int, err error)
}io.Reader interface
Simply implement the Read method on your type (or wrap it in one that does) and you can pass it in interchangabley
strings.Reader()
Question
Why would you use something like
strings.Reader()?
Answer
The purpose to wrap a string with the
Read()method so it meets the interface requirements ofio.Reader. Typically theRead()method is an abstraction for files, stdin, network connections - butstrings.NewReader()is a nice helper to wrap a plain string in that same abstraction.