Golang / GoLang Interfaces and Object Oriented Interview Questions
What is the zero value of an interface type and how does it differ from a zero-value struct?
Understanding zero values is essential for correct initialisation. Interface and struct zero values behave very differently.
// Zero value of a struct — all fields zeroed
type Config struct{ Host string; Port int; Debug bool }
var cfg Config // zero value: Config{Host:"", Port:0, Debug:false}
fmt.Println(cfg.Host) // "" — valid, ready to use
fmt.Println(cfg.Debug) // false
// Zero value of an interface — nil (both words zeroed)
var r io.Reader // nil interface
fmt.Println(r == nil) // true
// r.Read(buf) // PANIC: nil pointer dereference — no concrete impl
// Nil check before using interface
func useReader(r io.Reader) {
if r == nil {
log.Println("no reader provided")
return
}
io.Copy(os.Stdout, r)
}
// Structs designed to be useful at zero value (sync.Mutex, bytes.Buffer)
var mu sync.Mutex // zero value is a valid, unlocked mutex
mu.Lock()
defer mu.Unlock()
var buf bytes.Buffer // zero value is a valid empty buffer
buf.WriteString("hello")
// Interface containing a zero-value struct (NOT nil interface)
var c Config
var any interface{} = c // any is non-nil (type=Config, data=*Config zero)
fmt.Println(any == nil) // FALSE — interface holds a valueDesign goal: strive to make your types useful at their zero value (like sync.Mutex and bytes.Buffer). This means users do not need a constructor to get a valid instance. For interface types, the zero value is always nil — always check before dereferencing, or use the Null Object pattern to provide a safe no-op default.
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...
