0Pricing
Go Academy · Lesson

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

  1. Struct Embedding
  2. Interface Embedding
  3. Method Promotion
  4. Composition over Inheritance
← Back to Go Academy