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
}