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
- The embedded type's name is the field name.
- Promoted methods make the outer type satisfy the same interfaces.
- It is composition, not inheritance: no overriding, just shadowing.
Keywords and builtins used here
funcintreturnstringstructtype
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.
Step 3 of 3 in Structs & methods, step 3 of 19 in Interfaces & generics.