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