Golang / GoLang Interfaces and Object Oriented Interview Questions
What is the difference between embedding a struct and embedding an interface inside a struct?
Both look syntactically similar but have very different semantics and use cases:
| Aspect | Embed a struct | Embed an interface |
|---|---|---|
| Promoted methods | Real implementations from the embedded struct | Method signatures only — calls the interface field's concrete value |
| Zero value behaviour | Embedded struct's zero value is used | Nil interface — calling any method panics |
| Memory | Inline — embedded struct's fields are part of the outer struct | Two-word interface value (type + data) |
| Primary use | Code reuse — share method implementations | Partial mocking — satisfy a large interface by overriding only some methods |
// Embedding a STRUCT â real method reuse type Base struct{ ID int } func (b Base) Describe() string { return fmt.Sprintf("id=%d", b.ID) } type Derived struct { Base; Extra string } d := Derived{Base: Base{ID: 1}, Extra: "x"} d.Describe() // calls Base.Describe() â real implementation // Embedding an INTERFACE â partial mock pattern type Storage interface { Read(key string) ([]byte, error) Write(key string, val []byte) error Delete(key string) error List() ([]string, error) } // Test stub â only override Read; others panic (acceptable in tests) type ReadOnlyStub struct { Storage // embeds interface â zero value = nil data map[string][]byte } // Override only Read func (r ReadOnlyStub) Read(key string) ([]byte, error) { v, ok := r.data[key] if !ok { return nil, errors.New("not found") } return v, nil } // ReadOnlyStub satisfies Storage (via embedded interface promotion) // Calling Write, Delete, or List will panic â acceptable for a test stub var s Storage = ReadOnlyStub{data: map[string][]byte{"k": []byte("v")}} data, _ := s.Read("k") // works // s.Write("k", nil) // panics at runtime
What happens when you call a promoted method on an interface-embedded struct and the interface field is nil?
What is the primary use case for embedding an interface inside a struct?
More Related questions...