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
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...
