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