Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Go Struct Embedding: Composition over Inheritance and Method Shadowing

Promotion by depth, ambiguous selectors, embedded pointers that panic, why there is no virtual dispatch, and JSON flattening that drops shadowed fields.

~5 min readGo
#Go#Composition#Structs
3D illustration of inner struct components embedded into an outer wrapper struct with promoted methods

Struct embedding puts one type inside another without a field name, and Go promotes the inner type's fields and methods to the outer type. It is composition, not inheritance: there is no subtype relationship, no dynamic dispatch, and no way for the inner type's methods to call an outer override. What it does give is the shortest path to satisfying an interface by delegation, and a set of rules about depth and shadowing that decide which method a call actually reaches.

Quick Summary

  • An embedded field's name is its type name (Inner), and its fields and methods are promoted to the outer type.
  • Promotion is a depth rule: a field or method declared on the outer type shadows a promoted one at a shallower depth.
  • Two embedded types with the same field or method name at the same depth make the selector ambiguous — a compile error at the use site, not the declaration.
  • Embedding a pointer (*Inner) promotes the same methods but panics on any access when the pointer is nil.
  • The embedded type does not know about the outer type: an inner method calling another inner method calls the inner one, even if the outer shadows it.
  • Embedding an interface in a struct delegates the whole interface and makes the struct satisfy it, with a nil panic if the field is nil.
  • json flattens embedded struct fields into the outer object; embedded pointer fields are flattened too, and skipped when nil.
  • Embedding sync.Mutex promotes Lock and Unlock into the public API — usually a mistake, since it lets callers break the invariant.

Basic syntax and type signatures

go
type Base struct { ID string Created time.Time } func (b Base) Describe() string { return "id=" + b.ID } type User struct { Base // embedded value, field name Base Name string Email string } u := User{Base: Base{ID: "u1"}, Name: "ada"} fmt.Println(u.ID, u.Name) // promoted field fmt.Println(u.Describe()) // promoted method fmt.Println(u.Base.Describe()) // explicit path // Composite literals cannot use promoted fields: // u2 := User{ID: "u2"} // compile error: unknown field ID
go
type ReadWriter interface { io.Reader io.Writer } // interface embedding: composition of method sets type CountingWriter struct { io.Writer // embedded interface: delegation n int64 } func (c *CountingWriter) Write(p []byte) (int, error) { n, err := c.Writer.Write(p) c.n += int64(n) return n, err }

The field name is the unqualified type name, so embedding pkg.Inner gives the field name Inner; embedding two types with the same name from different packages requires an alias or a named field.

Comparison of embedding, named fields, and inheritance

AspectStruct embeddingNamed fieldInheritance (other languages)
Member accesspromoted (u.ID)qualified (u.Base.ID)inherited (u.ID)
Subtype relationshipnonenoneyes
Dynamic dispatchnonoyes
Overrideshadowing by name and depthn/avirtual override
Interface satisfactionpromoted methods countouter type must implementinherited
Composite literalneeds the embedded type's nameneeds the field nameconstructor
Ambiguitycompile error on same-depth clashimpossibledepends on language

The dispatch row is the one that trips up developers arriving from an object-oriented language: u.Describe() calls Base.Describe with u.Base as the receiver, and nothing in Base can call a User method.

Practical edge cases and deep dives

1. Shadowing by depth and the ambiguous selector

go
type Base struct{ Name string } func (b Base) Kind() string { return "base" } type Middle struct { Base Name string // shadows Base.Name at depth 1 } func (m Middle) Kind() string { return "middle" } type Outer struct { Middle Name string // shadows Middle.Name at depth 1 } o := Outer{Middle: Middle{Base: Base{Name: "deep"}, Name: "mid"}, Name: "outer"} fmt.Println(o.Name) // outer fmt.Println(o.Middle.Name) // mid fmt.Println(o.Middle.Base.Name) // deep fmt.Println(o.Kind()) // middle (the shallowest Kind)

The selector resolution rule is breadth-first by depth: the shallowest declaration wins, and if two declarations sit at the same depth, the selector is ambiguous.

go
type A struct{ ID string } type B struct{ ID string } type C struct { A B } var c C // fmt.Println(c.ID) // compile error: ambiguous selector c.ID fmt.Println(c.A.ID, c.B.ID) // must qualify

The error appears where the selector is used, not where C is declared, so a type can be embedded into a new combination months later and fail in code that never changed. The fix is either qualification or renaming the conflicting field on the outer type, which shadows both.

2. Method sets: embedded value versus embedded pointer

go
type Inner struct{ n int } func (i Inner) Value() int { return i.n } func (i *Inner) Inc() { i.n++ } type OuterValue struct{ Inner } type OuterPointer struct{ *Inner } var _ interface{ Value() int } = OuterValue{} // ok var _ interface{ Inc() } = &OuterValue{} // ok: *OuterValue has both // var _ interface{ Inc() } = OuterValue{} // error: Inc has pointer receiver var _ interface{ Value() int } = OuterPointer{} // ok var _ interface{ Inc() } = OuterPointer{} // ok: the embedded pointer supplies it

An embedded value promotes the inner type's methods according to the outer type's own method set rules, so *OuterValue gains Inc because it can take the address of the embedded field. An embedded pointer promotes everything immediately, to both OuterPointer and *OuterPointer — at the cost of a nil dereference if the field was never set:

go
type Service struct { *Inner // nil until assigned } func (s Service) Use() int { return s.Inc() // panic: runtime error: invalid memory address }

The pattern is safe only when the constructor guarantees the pointer, and a struct with an embedded pointer generally needs a constructor for that reason.

3. No virtual dispatch: the inner type cannot see the outer

go
type Animal struct{ name string } func (a Animal) Speak() string { return a.name + " makes a sound" } func (a Animal) Greet() string { return "I say: " + a.Speak() } type Dog struct { Animal } func (d Dog) Speak() string { return d.name + " barks" } d := Dog{Animal{name: "rex"}} fmt.Println(d.Speak()) // rex barks (outer method wins on the outer value) fmt.Println(d.Greet()) // I say: rex makes a sound (Animal.Greet calls Animal.Speak)

Greet was compiled against Animal.Speak, and embedding does not change that call. Any design that expects a base method to call an overridden one needs either an interface field, a function field, or an explicit parameter — embedding cannot express it. This is the structural reason Go codebases prefer small interfaces and explicit delegation over deep embedding hierarchies.

4. JSON flattening, and the fields that disappear

go
type Meta struct { CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` } type Post struct { Meta // flattened into the outer object Title string `json:"title"` } p := Post{Meta: Meta{CreatedAt: time.Now()}, Title: "hello"} b, _ := json.Marshal(p) // {"created_at":"...","updated_at":"0001-01-01T00:00:00Z","title":"hello"} type PostPtr struct { *Meta // flattened when non-nil, omitted when nil Title string `json:"title"` } b2, _ := json.Marshal(PostPtr{Title: "hello"}) // {"title":"hello"}

Embedding is how a shared set of columns gets flattened into several payloads without repeating the tags. Two rules to keep in mind: a name conflict between an outer field and a promoted one resolves in favor of the shallower field and the other is silently dropped from the JSON, and an embedded field's own json tag is ignored unless it has a name — Meta \json:"meta"`` turns flattening off and nests the object instead. Unmarshaling follows the same rules, so a payload that used to be nested stops filling the embedded struct the moment the tag is added.

5. Embedding locks and other types whose API should not leak

go
type Cache struct { sync.Mutex // Lock and Unlock become part of Cache's API m map[string]string } func (c *Cache) Get(k string) string { c.Lock() // caches are now lockable by callers defer c.Unlock() return c.m[k] } // A caller can do this, and nothing stops them: cache.Lock() defer cache.Unlock() cache.Get("k") // deadlock: the mutex is not reentrant

Embedding a mutex promotes Lock and Unlock to exported methods, so the type's public surface now includes a way to break its invariants, and go vet's copylocks check fires on every copy of the struct. The fix is a named field:

go
type Cache2 struct { mu sync.Mutex m map[string]string }

The same reasoning applies to embedding io.Reader in a struct that should expose only a higher-level method: promotion hands the whole interface to every caller. Embedding is best for types whose promoted surface is exactly what the outer type wants to offer — a Base with timestamps, a Validator with a Validate method, a small interface the outer type deliberately implements.

Common mistakes and compiler errors

Error or symptomCauseFix
ambiguous selector c.IDtwo embedded types declare the same name at the same depthqualify, or declare the field on the outer type
unknown field ID in struct literalpromoted fields cannot be set in a composite literalinitialize the embedded field by name
panic: invalid memory address on a promoted callembedded pointer is nilassign it in the constructor
Outer does not implement I (method has pointer receiver)embedding a value and using the value typeuse &Outer{}, or embed a pointer
An override is ignored by a base methodno dynamic dispatchpass the behavior in, or use an interface
JSON field disappearsa shallower field shadows the promoted onerename, or qualify with a tag
go vet: passes lock by valueembedded or copied mutexname the mutex field, use pointer receivers
Callers can Lock() the typeembedded sync.Mutexembed nothing; keep the lock private
Deep embedding chain is hard to followmethods promoted through three levelsflatten the struct
Interface method set unexpectedly largeembedded interface promotes everythingembed a narrower interface

The decision that keeps embedding useful is whether the promoted surface is intended. Embed when the outer type genuinely wants to offer every field and method of the inner type — a shared metadata block, a deliberately implemented interface, a small value type that gains a method by composition. Use a named field when the inner type is an implementation detail, when its methods would leak invariants, or when its name would collide with a concept the outer type exposes. The compiler will not tell the difference; the API will.

Try matching browser tools

All tools

Small utilities that fit Go work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Go guides

More in Go

All Go guides

The guides filed next to this one in Go, in library order.