Skip to content
Tutorials Center
My learning

Topics

Go Reference ยท Concepts

Go struct embedding

Reference for embedding in Go: promoted fields and methods, depth and ambiguity rules, embedding pointers and interfaces, why there is no virtual dispatch, and JSON.

Embedding means declaring a field with a type but no name. The field's name is then the type's name, and every exported and unexported field and method of the embedded type is promoted: you can write outer.Field instead of outer.Inner.Field. It is Go's tool for composition, and the only thing in the language that resembles inheritance, though it is not inheritance.

You can embed a struct type (Animal), a pointer to one (*Animal) or an interface (io.Reader). Promotion is a compile-time shortcut: the compiler writes forwarding methods for you. The embedded value is still an ordinary field that you can reach by its type name.

Go
type Animal struct{ Name string }

func (a Animal) Describe() string { return "I am " + a.Name }

type Dog struct {
	Animal // embedded
	Breed  string
}

Try it

Go Promotion and the explicit path

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Go No virtual dispatch, shadowing and ambiguity

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Syntax

Go
type Outer struct {
	Embedded       // value of type Embedded; field name "Embedded"
	*PtrEmbedded   // pointer; field name "PtrEmbedded"
	io.Reader      // interface; field name "Reader"
	pkg.Other      // qualified; field name "Other"
}

Selector resolution. For x.f, Go looks at the depth in the embedding tree where f is first found:

Situation Result
f declared directly on the struct That one is used (depth 0).
f found at exactly one shallowest depth That one is promoted. A shallower name hides deeper ones.
f found twice at the same shallowest depth Ambiguous: compile error, but only if you use x.f. The conflict itself is legal.

Promoted methods and method sets.

Struct contains Method set of S Method set of *S
embedded T methods with receiver T receiver T and *T
embedded *T receiver T and *T receiver T and *T

Constraints: a type cannot embed itself directly (type T struct{ T } is invalid; *T is allowed). An embedded type must be a type name T or a pointer to a non-interface type name *T; *I for an interface I is illegal. Two embedded fields cannot have the same name, which includes T and *T together.

Edge cases: the promoted method runs with the embedded value as its receiver. Embedding a nil pointer compiles, and a promoted call through it panics if the method dereferences the receiver.

Usage notes

  • There is no virtual dispatch. Base.Hello calls Base.Name, never the Derived version, since Base knows nothing about Derived. If you want customization, pass an interface or function in explicitly.
  • Composition, not "is-a". Dog is not an Animal for assignment: var a Animal = dog fails. Use an interface that both satisfy.
  • Embedding an interface gives a struct the interface's methods; the wrapper can override just one. This is how bufio.ReadWriter and many test doubles work: embed the interface, then define only the method you want to change. Calls to the others panic if the embedded interface is nil.
  • Interface embedding inside another interface merges method sets (io.ReadWriter embeds Reader and Writer). Overlapping methods with identical signatures are allowed (Go 1.14).
  • Exported-ness follows the type name. Embedding an unexported type from your own package promotes its exported methods to outside users, which is a handy way to hide the type itself.
  • JSON. encoding/json flattens the fields of an embedded struct into the outer object, unless you give the embedded field a tag name. Name conflicts follow the same depth rule.
  • Struct literals must name the embedded field: Dog{Animal: Animal{Name: "Rex"}}. The promoted field Name cannot be set directly in a literal.
  • Mutex embedding. type SafeMap struct{ sync.Mutex; m map[string]int } exposes Lock and Unlock to users. A named field (mu sync.Mutex) is usually better, since it keeps locking an internal detail.