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