Programming Languages
Go
Subjective
Oct 04, 2025
What is embedding in Go and how does it work?
Detailed Explanation
Embedding in Go:
• Composition mechanism (not inheritance)
• Embed types in structs
• Promotes embedded type's methods
• Access embedded fields directly
• Enables polymorphism
Example:
type Engine struct {
Power int
}
func (e Engine) Start() {
fmt.Println("Engine starting")
}
type Car struct {
Engine // embedded
Brand string
}
car := Car{Engine{200}, "Toyota"}
car.Start() // calls Engine.Start()
car.Engine.Start() // explicit access
Discussion (0)
No comments yet. Be the first to share your thoughts!
Share Your Thoughts