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