What Is the io.Reader Interface and Why Is It Everywhere

The io.Reader interface defines a standard Read method for streaming data, enabling Go code to handle files, networks, and buffers uniformly.

The io.Reader interface is a contract that any type can implement to provide a stream of bytes by defining a single Read method. It is ubiquitous in Go because it allows functions to accept any data sourceβ€”files, network connections, or memory buffersβ€”without needing to know the specific underlying type. Implementing it requires defining a Read method that fills a provided byte slice and returns the number of bytes read or an error.

type Reader interface {
    Read(p []byte) (n int, err error)
}
// Example: A simple reader that returns "Hello"
func (r *HelloReader) Read(p []byte) (n int, err error) {
    if r.done {
        return 0, io.EOF
    }
    n = copy(p, []byte("Hello"))
    r.done = true
    return n, nil
}