Embedded Structs
Go does not have classes or classical inheritance. Instead, it uses embedded structs to provide a similar benefit of sharing fields between types.
Promotion
When you include a struct type within another struct without a field name, it is “embedded.” All the fields of the embedded struct are “promoted” to the top level of the parent struct.
type car struct {
brand string
model string
}
type truck struct {
car // Embedded!
bedSize int
}
myTruck := truck{
bedSize: 10,
car: car{brand: "Ford", model: "F150"},
}
// Access promoted fields directly
fmt.Println(myTruck.brand) // Ford
Embedded vs. Nested
- Nested: You must access fields through the property name (
truck.car.brand). - Embedded: You access fields as if they were on the parent struct (
truck.brand).
This is often used to compose larger structs out of smaller, reusable pieces without creating deep hierarchies.