Struct Embedding
-
Struct embedding (also called "anonymous fields") is Go’s way of
practicing
Composition.
A struct can include another struct as a field without a name
type Engine struct {
yearofmake int
}
func (e Engine) Start() {
fmt.Println("Engine started")
}
type Car struct {
Engine // This is an embedded field
Model string
}
func main() {
c := Car{
Engine: Engine{yearofmake: 2000},
Model: "Sedan",
}
// You can access fields and methods of Engine directly on Car
fmt.Println(c.yearofmake)
c.Start()
}