Golang / GoLang Interfaces and Object Oriented Interview Questions
How does Go's standard library use interface layering for I/O transformation?
The I/O stack in Go is built by wrapping interfaces. Each layer satisfies io.Reader or io.Writer and wraps the previous layer, adding one transformation: buffering, compression, encryption, counting. No layer modifies the others — they compose transparently.
// Layer by layer: file → gzip → bufio → hash → tee
f, err := os.Create("output.gz")
if err != nil { log.Fatal(err) }
defer f.Close()
// Layer 1: gzip compression on top of the file
gz := gzip.NewWriter(f) // satisfies io.WriteCloser
defer gz.Close()
// Layer 2: buffering on top of gzip
buf := bufio.NewWriter(gz) // satisfies io.Writer
// Layer 3: SHA-256 hash computation alongside writing
h := sha256.New() // satisfies io.Writer
tee := io.MultiWriter(buf, h) // writes to both buf and hash
// Write data — single Write call propagates through all layers
fmt.Fprintln(tee, "Hello, World!") // → buf → gz → f; also → h
buf.Flush() // flush buffered data into gzip
sum := h.Sum(nil)
fmt.Printf("SHA-256: %x\n", sum)
// Reading side
f2, _ := os.Open("output.gz")
defer f2.Close()
gzr, _ := gzip.NewReader(f2) // io.Reader that decompresses
buf2 := bufio.NewReader(gzr) // io.Reader that buffers
limited := io.LimitReader(buf2, 1024) // io.Reader that stops at 1 KB
data, _ := io.ReadAll(limited) // reads through all three layers
fmt.Println(string(data))Each layer is oblivious to the others. gzip.NewReader doesn't know if it's wrapping a file or a network connection; bufio.NewReader doesn't know about compression. This is the Decorator pattern executed through Go interfaces: behaviours stack without modifying each other.
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...
