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 stdoutThe 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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
