typestar

Struct embedding in Go

Embedding promotes the inner type's fields and methods to the outer one.

type Base struct {
    ID      int
    Created string
}

func (b Base) Age() string { return "since " + b.Created }

type Tour struct {
    Base
    Slug  string
    Steps int
}

func (t Tour) Describe() string {
    return fmt.Sprintf("%s #%d %s, %d steps",
        t.Slug, t.ID, t.Age(), t.Steps)
}

func build() string {
    tour := Tour{Base: Base{ID: 3, Created: "2026-07"}, Slug: "traits",
        Steps: 19}
    return tour.Describe()
}

How it works

  1. The embedded type's name is the field name.
  2. Promoted methods make the outer type satisfy the same interfaces.
  3. It is composition, not inheritance: no overriding, just shadowing.

Keywords and builtins used here

The run, in numbers

Lines
23
Characters to type
395
Tokens
110
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 69 seconds.

Type this snippet

Step 3 of 3 in Structs & methods, step 3 of 19 in Interfaces & generics.

← Previous Next →