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.
More Related questions...