Golang / GoLang Interfaces and Object Oriented Interview Questions
How does embedding help a struct satisfy an interface?
When a struct embeds another type, it promotes the embedded type's methods. If those promoted methods complete an interface's method set, the outer struct implicitly satisfies the interface — without writing any wrapper code.
type Sayer interface{ Say() string }
type Greeter struct{}
func (g Greeter) Say() string { return "Hello!" }
// By embedding Greeter, Robot satisfies Sayer without implementing Say itself
type Robot struct {
Greeter // promotes Say()
Model string
}
var s Sayer = Robot{Greeter: Greeter{}, Model: "R2D2"}
fmt.Println(s.Say()) // Hello! — dispatched to Greeter.Say()
// Override: Robot can provide its own Say() to shadow the promoted one
func (r Robot) Say() string { return "Beep boop from " + r.Model }
// Now Robot.Say() is called, not Greeter.Say()
// Partial interface satisfaction via embedding
type ReadWriter interface {
Read(p []byte) (int, error)
Write(p []byte) (int, error)
}
type MyBuffer struct {
bytes.Buffer // provides both Read and Write
}
var rw ReadWriter = &MyBuffer{} // satisfied via embedded bytes.Buffer
// Embedding an interface inside a struct
// (used to implement partial/stub implementations in tests)
type MockDB struct {
Database // interface embedded — zero value methods panic
}
// Override only the methods you care about in the test
func (m MockDB) Query(sql string) (Rows, error) { return testRows, nil }Embedding an interface inside a struct is an advanced pattern: all the interface methods are promoted and the zero value is nil (all methods panic). Override only the methods needed for a test — a compact way to implement a partial mock without satisfying every method of a large interface.
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...
