Embedding - Composition Over Inheritance | Learn Golang #18
Video: Embedding - Composition Over Inheritance | Learn Golang #18 by Taught by Celeste AI - AI Coding Coach
Take the quiz on the full lesson page
Test what you've read · interactive walkthrough
Embedding - Composition Over Inheritance in Go
In Go, struct embedding allows you to compose types by including one struct within another, promoting its fields and methods directly on the outer struct. This approach enables code reuse and flexible design without traditional inheritance, embracing composition as the preferred pattern.
Code
package main
import "fmt"
// Base struct with fields and methods
type Animal struct {
Name string
}
func (a Animal) Speak() {
fmt.Println(a.Name, "makes a sound")
}
// Embedding Animal inside Dog
type Dog struct {
Animal // Embedded struct; its fields and methods are promoted
Breed string
}
// Override Speak method for Dog
func (d Dog) Speak() {
fmt.Println(d.Name, "barks")
}
func main() {
d := Dog{
Animal: Animal{Name: "Buddy"},
Breed: "Golden Retriever",
}
// Access embedded field directly
fmt.Println("Dog's name:", d.Name)
// Call overridden method
d.Speak() // Output: Buddy barks
// Call embedded method explicitly
d.Animal.Speak() // Output: Buddy makes a sound
}
Key Points
- Embedding a struct promotes its fields and methods, making them accessible directly on the outer struct.
- Go uses composition over inheritance, favoring embedding to reuse code and extend behavior.
- Methods can be overridden by defining a method with the same name on the embedding struct.
- Multiple and nested embedding allow flexible and modular type composition.
- Interfaces can also be embedded in structs, enabling polymorphic behavior with composition.
Ready? Take the quiz on the full lesson page →
Test what you've learned. Watch the lesson and try the interactive quiz on the same page.