Golang / GoLang Interfaces and Object Oriented Interview Questions
What is the interface upgrade (optional interface) pattern in Go?
The interface upgrade pattern lets code check whether an interface value's concrete type also satisfies a more capable (optional) interface, and use the enhanced behaviour if available — without requiring all implementations to support it. This is how the Go standard library achieves extensibility.
// Basic interface — all implementations must satisfy
type Writer interface {
Write(p []byte) (int, error)
}
// Enhanced optional interface
type StringWriter interface {
WriteString(s string) (int, error)
}
// Function accepting Writer — works with any Writer
// but uses WriteString if available (avoids []byte conversion)
func writeString(w Writer, s string) (int, error) {
// Interface upgrade: check if w also supports WriteString
if sw, ok := w.(StringWriter); ok {
return sw.WriteString(s) // faster path
}
return w.Write([]byte(s)) // fallback
}
// This is exactly how bufio.Writer in the stdlib does it:
// bufio.Writer.WriteString checks if the underlying writer
// implements WriteString and avoids the []byte allocation
// Another real example: http.Flusher
func streamResponse(w http.ResponseWriter, data []byte) {
w.Write(data)
// Check if the ResponseWriter supports streaming flush
if flusher, ok := w.(http.Flusher); ok {
flusher.Flush() // sends bytes to client immediately
}
}
// http.Hijacker — upgrade ResponseWriter to take over TCP connection
// http.CloseNotifier — deprecated, but same pattern
// io.WriterTo, io.ReaderFrom — upgrade for efficient copyThe upgrade pattern lets the standard library evolve without breaking existing code: a new optional interface can be added, and implementations that want the enhanced behaviour can opt in. Code that only has the basic interface continues working. This is much more flexible than adding a method to an existing interface (which would break all existing implementations).
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...
