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