Golang / Golang Internals and Memory Management Interview Questions
How do io.Reader and io.Writer work and why are they fundamental to Go's I/O model?
io.Reader and io.Writer are the two most important interfaces in the Go standard library. Their simplicity (one method each) enables an enormous amount of composition and abstraction across files, network connections, bytes buffers, gzip streams, crypto, and more.
// The core interfaces:
// type Reader interface { Read(p []byte) (n int, err error) }
// type Writer interface { Write(p []byte) (n int, err error) }
// io.Copy — generic transfer between any Reader and Writer
func Copy(dst io.Writer, src io.Reader) (written int64, err error)
// Examples of io.Reader implementations:
// *os.File, *bytes.Buffer, *strings.Reader, net.Conn, *gzip.Reader
// http.Response.Body, *bufio.Reader, *io.LimitedReader
// Composing readers
func processRequest(r *http.Request) {
// Layer buffering, decompression, and limiting in one chain
limited := io.LimitReader(r.Body, 10<<20) // max 10 MB
gzr, _ := gzip.NewReader(limited) // decompress
buffered := bufio.NewReader(gzr) // buffer reads
// Now read from buffered — all layers transparent
line, _, _ := buffered.ReadLine()
fmt.Println(string(line))
}
// Custom Reader — generate Fibonacci numbers as bytes
type FibReader struct{ a, b int }
func (f *FibReader) Read(p []byte) (int, error) {
if len(p) == 0 { return 0, nil }
n := copy(p, []byte(fmt.Sprintf("%d ", f.a)))
f.a, f.b = f.b, f.a+f.b
return n, nil // io.EOF to signal end of stream
}
// io.TeeReader — read from r while writing to w simultaneously
var buf bytes.Buffer
tee := io.TeeReader(r.Body, &buf) // buf captures what is read from r.Body
io.Copy(downstream, tee)The Read contract: a successful read returns n > 0, err == nil or final data with err == io.EOF. A Read may return n > 0 together with io.EOF in the same call. Callers must process the n bytes before inspecting the error. Never assume Read fills the entire buffer — always loop until io.EOF or use io.ReadFull.
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...
