Golang / GoLang Interfaces and Object Oriented Interview Questions
How does embedding propagate interface satisfaction through multiple levels?
Embedding is transitive. If type C embeds type B which embeds type A, then C's method set includes all methods from A and B. This means C can satisfy interfaces that A satisfies — through a chain of embeddings.
type Named interface { Name() string }
type Described interface { Describe() string }
type NamedAndDescribed interface { Named; Described }
// Level 1
type Animal struct{ name string }
func (a Animal) Name() string { return a.name }
// Level 2 — embeds Animal
type Pet struct {
Animal
Owner string
}
func (p Pet) Describe() string {
return fmt.Sprintf("%s owned by %s", p.Name(), p.Owner)
}
// Level 3 — embeds Pet
type ServiceAnimal struct {
Pet
BadgeID string
}
// ServiceAnimal inherits Name() from Animal (via Pet) and
// Describe() from Pet
sa := ServiceAnimal{
Pet: Pet{
Animal: Animal{name: "Rex"},
Owner: "Alice",
},
BadgeID: "K9-042",
}
var nd NamedAndDescribed = sa // ServiceAnimal satisfies NamedAndDescribed
fmt.Println(nd.Name()) // Rex
fmt.Println(nd.Describe()) // Rex owned by Alice
// Method ambiguity: what if both A and B define the same method?
type X struct { Val int }; func (x X) Tag() string { return "X" }
type Y struct { Val int }; func (y Y) Tag() string { return "Y" }
type Ambiguous struct { X; Y }
// a := Ambiguous{}; a.Tag() // COMPILE ERROR: ambiguous selector a.Tag
// Must qualify: a.X.Tag() or a.Y.Tag()Disambiguation rule: if two embedded types provide a method with the same name at the same depth, accessing that method on the outer struct is a compile error. The solution is to define the method explicitly on the outer type, which takes precedence and resolves the ambiguity.
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...
