Skip to the workspace
Pebellslearn by building
Maps & Structs  ›  Capstone Project

Embedding Structs

Embedding Structs 16 minEmbedding a struct type as an unnamed field promotes its fields and methods to the outer struct, which is composition rather than inheritance: the outer type contains the inner one but is not a kind of it.

golang / Embedding Structs

Explore each scene at your own pace.

01 · The rule

The rule

Embedding Structs

Embedding a struct type as an unnamed field promotes its fields and methods to the outer struct, which is composition rather than inheritance: the outer type contains the inner one but is not a kind of it.

Follow promoted fields and methods without treating embedding as class inheritance.

tally reports on one file at a time, but a new feature will summarise many files. Both reports need the same core numbers — total words, unique words — plus their own extras. Rather than copy those fields into every struct, Go lets you embed one struct inside another.

The rule

Embed to contain: inner fields and methods are promoted, but it is not inheritance.

type Stats struct {
	Total  int `json:"total"`
	Unique int `json:"unique"`
}

func (s Stats) Repeats() int { return s.Total - s.Unique }

type Report struct {
	Stats             // embedded: a field with no name
	File string `json:"file"`
}

An embedded field is written as just a type. Its field name is the type's name, Stats.

Promoted. The inner fields and methods can be reached as if they belonged to the outer struct:

r := Report{Stats: Stats{Total: 17, Unique: 12}, File: "notes.txt"}
fmt.Println(r.Total)     // 17, short for r.Stats.Total
fmt.Println(r.Repeats()) // 5,  short for r.Stats.Repeats()

Note the literal: you still build the embedded part by its type name, Stats: Stats{...}.

Not inheritance. A Report contains a Stats; it is not a kind of Stats. A function show(s Stats) will not accept r — you pass r.Stats. (Promoted methods do let Report satisfy interfaces that Stats satisfies, which you will meet with interfaces.)

Embedding many types is allowed. If two embedded structs at the same depth both have a Total, writing r.Total becomes a compile error (ambiguous selector), and you must name the one you mean, such as r.Stats.Total.

Name clashes. If Report declares its own Total, the outer field wins: r.Total is Report's, and the inner one is still r.Stats.Total.

JSON flattens. encoding/json treats the promoted fields as if they were declared in the outer struct:

data, _ := json.Marshal(r)
fmt.Println(string(data))
// {"total":17,"unique":12,"file":"notes.txt"}
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.