Skip to content
Codewilds

Lesson 24 of 38 · Structs & Methods

Go Struct Embedding and Composition

medium20 XP4 min read

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{...}).

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 Dog can't be passed as an Animal, and the embedded type's methods never call the outer type's shadowing methods.
  • A literal without the embedded type: Dog{Name: "Rex"} fails with unknown field Name in struct literal. Write Dog{Animal: Animal{Name: "Rex"}}.
  • Calling yourself by accident: inside Cat.Describe, writing c.Describe() instead of c.Animal.Describe() calls Cat.Describe again, forever.
  • Embedding a pointer and leaving it nil: with type Dog struct { *Animal }, reading Dog{}.Name panics because there is no Animal yet.

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:

  1. TakeDamage(n int) lowers HP by n, but HP never drops below 0. Zero or negative n changes nothing.
  2. IsAlive() bool reports whether HP is above 0.
  3. Describe() string returns "<Name> (HP <HP>)", e.g. "Slime (HP 12)".

Then write:

  1. (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)". Reuse h.Entity.Describe(). Monsters have no Describe of their own, so they use the promoted one.
  2. Battle(h *Hero, m *Monster, rounds int) bool, which fights for at most rounds rounds. In each round the monster takes 10 * h.Level damage. If it is no longer alive, the hero gains a level and Battle returns true. Otherwise the hero takes m.Damage damage, and if the hero is no longer alive, Battle returns false. If the rounds run out first, it returns false.
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
Play the 9 free lessons

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

Need a quick reminder? The Go cheat sheet has every topic of Learn Go on one page.

Lesson last updated on .

Write code ↓
Go+20 XP

Lesson 24 is part of the full course. The first 9 lessons are free.

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
Play the 9 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.