Golang / GoLang Interfaces and Object Oriented Interview Questions
How do io.Reader and io.Writer demonstrate Go's interface design philosophy?
io.Reader and io.Writer are the most influential interfaces in the Go standard library. They each have exactly one method, yet they model an enormous variety of data sources and sinks — files, network connections, byte buffers, compression streams, crypto pipes, and more.
// io.Reader and io.Writer â the entire interface type Reader interface { Read(p []byte) (n int, err error) } type Writer interface { Write(p []byte) (n int, err error) } // Composition: ReadWriter, ReadCloser, WriteCloser type ReadWriter interface { Reader; Writer } type ReadCloser interface { Reader; Closer } type WriteCloser interface { Writer; Closer } // Any function accepting io.Reader can work with ALL of these: func countBytes(r io.Reader) (int64, error) { return io.Copy(io.Discard, r) } // Works identically for: f, _ := os.Open("data.txt") countBytes(f) // *os.File countBytes(strings.NewReader("hello")) // *strings.Reader countBytes(bytes.NewReader(data)) // *bytes.Reader countBytes(resp.Body) // http.Response.Body countBytes(gzip.NewReader(f)) // *gzip.Reader // Composing transforms: gzip decompress â buffered read â count f2, _ := os.Open("archive.gz") gzr, _ := gzip.NewReader(f2) buf := bufio.NewReader(gzr) count, _ := countBytes(buf) // Each layer is transparent to countBytes â it just calls Read() // Writing to multiple destinations simultaneously var buf2 bytes.Buffer multi := io.MultiWriter(&buf2, os.Stdout) fmt.Fprintln(multi, "hello") // writes to both buf2 and stdout
The lesson: small interfaces with well-chosen methods compose powerfully. By accepting io.Reader instead of *os.File, a function becomes universally useful. Each layer in the stack (file, gzip, bufio) wraps the previous one, extending behaviour without modifying the original — the Decorator pattern in Go.
More Related questions...