~/Golang Reader and Writer Interfaces Explained with Examples

Mar 22, 2019


The io.Reader and io.Writer interfaces are essential for input and output in Go.

A Reader is any type that implements the method

1
Read(p []byte) (n int, err error)

A Writer is any type that implements the method

1
Write(p []byte) (n int, err error)

To write your own, define a type with either method signature.

Example - A Simple Reader:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
type stringReader struct {
    s   string
    off int
}
func (r *stringReader) Read(p []byte) (int, error) {
    if r.off >= len(r.s) {
        return 0, io.EOF
    }
    n := copy(p, r.s[r.off:])
    r.off += n
    return n, nil
}

Example - A Simple Writer:

1
2
3
4
5
6
7
type bufferWriter struct {
    buf []byte
}
func (w *bufferWriter) Write(p []byte) (int, error) {
    w.buf = append(w.buf, p...)
    return len(p), nil
}

When implementing Reader, return io.EOF when complete. For Writer, always report bytes written and any errors. Follow examples in the Go standard library.

For a deeper dive, see the Go Blog on Readers and Writers.

Tags: [golang]