Struct Embedding
Compose structs.
Compose Structs
Go has no class inheritance. Instead it offers embedding: place one struct inside another without a field name to reuse its fields and methods.
Anonymous Fields
An embedded field is declared by type only, no name. Its members are promoted to the outer struct.
package main
import "fmt"
type Engine struct{ Power int }
type Car struct {
Engine
Brand string
}
func main() {
c := Car{Engine: Engine{Power: 150}, Brand: "Coddy"}
fmt.Println(c.Power, c.Brand)
}All lessons in this course
- Struct Embedding
- Interface Embedding
- Method Promotion
- Composition over Inheritance