Lesson 24 of 38 · Structs & Methods
Go Struct Embedding and Composition
Big types are usually built from smaller ones: a hero has health, a car has an engine. Many languages model this with classes and inheritance — Go has neither. Instead, it lets you embed one struct type inside another, and the outer struct automatically gains the inner one's fields and methods.
This is called composition, and it's the idiomatic way to share data and behaviour between Go types.
Embedding a struct
To embed a type, list it inside a struct without a field name:
type Animal struct {
Name string
Legs int
}
func (a *Animal) Describe() string {
return fmt.Sprintf("%s has %d legs", a.Name, a.Legs)
}
type Dog struct {
Animal // embedded: a type without a field name
Breed string
}
func main() {
d := Dog{
Animal: Animal{Name: "Rex", Legs: 4},
Breed: "Beagle",
}
fmt.Println(d.Name, d.Breed) // promoted field
fmt.Println(d.Describe()) // promoted method
fmt.Printf("%+v\n", d)
}
Rex Beagle
Rex has 4 legs
{Animal:{Name:Rex Legs:4} Breed:Beagle}
The embedded struct is still an ordinary field, named after its type: d.Animal. Its fields and methods are promoted to the outer struct, so d.Name is shorthand for d.Animal.Name and d.Describe() for d.Animal.Describe(). In a struct literal you must spell the embedded value out (Animal: Animal{...}).
Promoted pointer methods
Describe has a pointer receiver, yet d.Describe() works on the variable d: Go calls (&d.Animal).Describe(). So a promoted pointer method changes the embedded part inside the outer value:
type Health struct {
HP int
}
func (h *Health) Damage(n int) {
h.HP -= n
}
type Knight struct {
Health
Name string
}
k := Knight{Health: Health{HP: 30}, Name: "Lance"}
k.Damage(12) // (&k.Health).Damage(12)
fmt.Println(k.HP) // 18
Shadowing a method
When the outer type declares a field or method with the same name as a promoted one, the outer one wins: it shadows the promoted name. The embedded version is still reachable through the explicit path:
type Cat struct {
Animal
}
// Describe shadows the promoted Animal.Describe.
func (c *Cat) Describe() string {
return "the cat " + c.Animal.Describe()
}
func (a *Animal) Introduce() string {
return "Hello! " + a.Describe()
}
tom := Cat{Animal: Animal{Name: "Tom", Legs: 4}}
fmt.Println(tom.Describe())
fmt.Println(tom.Animal.Describe())
fmt.Println(tom.Introduce())
the cat Tom has 4 legs
Tom has 4 legs
Hello! Tom has 4 legs
Look at the last line. Shadowing resembles overriding in object-oriented languages, but it isn't: Introduce is a method of Animal, so its call a.Describe() always runs Animal's version. The embedded value doesn't know it lives inside a Cat.
Composition, not inheritance
A Dog contains an Animal, but it is not an Animal. A function that expects an *Animal won't accept a *Dog:
func feed(a *Animal) {
fmt.Println("Feeding", a.Name)
}
feed(&d.Animal) // OK: pass the embedded part
// feed(&d) is a compile error:
// cannot use &d (value of type *Dog) as *Animal value
When one function should work with many types — "anything that can Describe itself" — Go uses interfaces, coming in the next chapter.
Name conflicts
A name declared directly on the outer struct always beats a promoted one. But if two embedded structs at the same depth both provide the same name, neither is promoted:
type Engine struct{ Name string }
type Radio struct{ Name string }
type Car struct {
Engine // has a Name field
Radio // has a Name field too
Model string
}
c := Car{Engine: Engine{Name: "V8"}, Radio: Radio{Name: "FM"}, Model: "Roadster"}
fmt.Println(c.Engine.Name, c.Radio.Name) // V8 FM
Writing c.Name here is a compile error (ambiguous selector c.Name), so you spell out the path instead.
Common mistakes
- Expecting inheritance: a
Dogcan't be passed as anAnimal, and the embedded type's methods never call the outer type's shadowing methods. - A literal without the embedded type:
Dog{Name: "Rex"}fails withunknown field Name in struct literal. WriteDog{Animal: Animal{Name: "Rex"}}. - Calling yourself by accident: inside
Cat.Describe, writingc.Describe()instead ofc.Animal.Describe()callsCat.Describeagain, forever. - Embedding a pointer and leaving it nil: with
type Dog struct { *Animal }, readingDog{}.Namepanics because there is noAnimalyet.
Assignment
Build the core of a battle system. The starter declares three types:
type Entity struct {
Name string
HP int
}
type Hero struct {
Entity
Level int
}
type Monster struct {
Entity
Damage int
}
Give Entity three methods, all with pointer receivers:
TakeDamage(n int)lowersHPbyn, butHPnever drops below0. Zero or negativenchanges nothing.IsAlive() boolreports whetherHPis above0.Describe() stringreturns"<Name> (HP <HP>)", e.g."Slime (HP 12)".
Then write:
(h *Hero) Describe() string, which shadows the promoted method and returns"Lv <Level> "followed by the entity's description, e.g."Lv 3 Ada (HP 90)". Reuseh.Entity.Describe(). Monsters have noDescribeof their own, so they use the promoted one.Battle(h *Hero, m *Monster, rounds int) bool, which fights for at mostroundsrounds. In each round the monster takes10 * h.Leveldamage. If it is no longer alive, the hero gains a level andBattlereturnstrue. Otherwise the hero takesm.Damagedamage, and if the hero is no longer alive,Battlereturnsfalse. If the rounds run out first, it returnsfalse.
ada := Hero{Entity: Entity{Name: "Ada", HP: 100}, Level: 2}
slime := Monster{Entity: Entity{Name: "Slime", HP: 50}, Damage: 15}
fmt.Println(Battle(&ada, &slime, 5)) // true (the slime falls in round 3)
fmt.Println(ada.Describe()) // Lv 3 Ada (HP 70)
fmt.Println(slime.Describe()) // Slime (HP 0)Premium lesson
Unlock the full Learn Go course
- All 38 lessons, bosses and quizzes — lifetime access
- One payment of $35, no subscription
- Finish within 30 days and claim $10.50 (30%) back
Want more than one course?
The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.
Inheritance in other languages
- JavaScript Inheritance: extends, super and static · JavaScript
- Python Inheritance and super() · Python
- Java Inheritance: extends and super · Java
- C# Inheritance: virtual, override and base · C#
Need a quick reminder? The Go cheat sheet has every topic of Learn Go on one page.
Lesson last updated on .