Golang / GoLang Interfaces and Object Oriented Interview Questions
How does Go implement code reuse without inheritance? Explain composition via struct embedding.
Go has no class hierarchy and no inheritance. Code reuse is achieved through composition: embedding one struct inside another promotes the embedded type's methods and fields to the outer type. This gives the outer type the embedded type's capabilities without any parent-child relationship.
// Base 'class' — a plain struct
type Animal struct {
Name string
Age int
}
func (a Animal) Describe() string {
return fmt.Sprintf("%s (age %d)", a.Name, a.Age)
}
// Composition: Dog embeds Animal
type Dog struct {
Animal // embedded — methods and fields promoted
Breed string
}
func (d Dog) Sound() string { return "Woof" }
d := Dog{
Animal: Animal{Name: "Rex", Age: 3},
Breed: "Labrador",
}
fmt.Println(d.Describe()) // promoted — same as d.Animal.Describe()
fmt.Println(d.Name) // promoted field access
fmt.Println(d.Sound()) // Dog's own method
// Method overriding via shadowing
type PoliceDog struct {
Dog
BadgeNumber int
}
// PoliceDog can shadow Dog's promoted methods:
func (p PoliceDog) Sound() string {
return "Woof! Police K9 #" + strconv.Itoa(p.BadgeNumber)
}
pd := PoliceDog{Dog: d, BadgeNumber: 42}
fmt.Println(pd.Sound()) // PoliceDog.Sound() — shadows Dog.Sound()
fmt.Println(pd.Dog.Sound()) // explicit Dog.Sound() — bypasses shadow
fmt.Println(pd.Describe()) // still promoted from AnimalKey distinction from inheritance: embedding is a mechanical promotion of methods, not an IS-A relationship. A PoliceDog is not a subtype of Dog — you cannot pass a PoliceDog where a Dog is expected (unless they share an interface). If both share an interface and implement all its methods, both can be used through that 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...
