Go Struct Embedding Explained with Examples

Updated 4 min read
Go Struct Embedding featured image: cards for embedding, promoted fields and overriding

Go struct embedding lets you place one struct inside another so the outer struct reuses its fields and methods. In this post, you will see promoted fields, promoted methods, overriding and how embedding helps with interfaces. Each idea comes with a short example that you can run yourself.

First, make sure you are comfortable with structs and methods in Go. We will also satisfy interfaces through embedding, so interfaces in Go with examples is a useful refresher.

What Is Go Struct Embedding?

Go has no classes and no inheritance. Instead, it prefers composition, which means building bigger types from smaller ones. Embedding is the shortcut for that. You list a type inside a struct without giving it 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, no field name
	Breed  string
}

Think of a phone with a built-in camera. The phone does not become a camera, but you can still press the camera button directly on the phone.

d := Dog{Animal: Animal{Name: "Bruno", Legs: 4}, Breed: "Labrador"}
fmt.Println(d.Name, d.Legs, d.Breed) // Bruno 4 Labrador
fmt.Println(d.Describe())            // Bruno has 4 legs
fmt.Printf("%+v\n", d)               // {Animal:{Name:Bruno Legs:4} Breed:Labrador}

You can write d.Name instead of d.Animal.Name. In other words, Go “promotes” the inner fields and methods to the outer struct. However, the inner struct still exists, and its field name is simply its type name, Animal.

Overriding Methods in Go Struct Embedding

func (a Animal) Sound() string { return "..." }
func (d Dog) Sound() string    { return "Woof" }

fmt.Println(d.Sound())        // Woof
fmt.Println(d.Animal.Sound()) // ...

When both types have a method with the same name, the outer one wins. The diagram below shows how Go looks up d.Name and d.Sound().

Go Struct Embedding diagram showing how Go looks up d.Sound and d.Name in a Dog that embeds Animal

Go checks the outer struct first and then the embedded struct, so Dog’s own Sound wins while Name comes from Animal.

The inner method is still reachable through d.Animal.Sound(). So you can call it when the outer method wants to add to it rather than replace it.

Go Struct Embedding and Interfaces

type Speaker interface{ Sound() string }

var sp Speaker = d
fmt.Println(sp.Sound()) // Woof

Promoted methods count toward interfaces. As a result, a struct can satisfy an interface using methods it gets from an embedded type.

Reusing Helpers Like a Logger

type Logger struct{ Prefix string }

func (l Logger) Log(msg string) { fmt.Println(l.Prefix + msg) }

type Service struct {
	Logger
	Name string
}

s := Service{Logger: Logger{Prefix: "[orders] "}, Name: "orders"}
s.Log("service started") // [orders] service started

This is the most common real use of Go struct embedding. Small helper types add shared behaviour to many services without copy-paste. For example, many programs embed sync.Mutex so a struct gains Lock and Unlock.

Embedding sync.Mutex

type Counter struct {
	sync.Mutex
	n int
}

func (c *Counter) Inc() {
	c.Lock()
	defer c.Unlock()
	c.n++
}

Here c.Lock() is really c.Mutex.Lock(), promoted from the embedded mutex. So the counter is safe to use from many goroutines, as you saw in the Go sync package. However, keep in mind that embedding also exports Lock to every caller. If you want to hide it, use a named field like mu sync.Mutex instead.

Embedding Is Not Inheritance

func show(a Animal) {}

show(d)
// cannot use d (variable of struct type Dog) as Animal value in argument to show

A Dog is not an Animal in Go. Therefore, you cannot pass it where an Animal is expected. Pass d.Animal instead, or better, accept an interface. This keeps Go struct embedding simple and predictable.

Common Mistakes with Go Struct Embedding

Error you seeWhy it happensHow to fix it
ambiguous selector c.NameTwo embedded structs both have Name.Write c.A.Name or c.B.Name.
cannot use d (variable of struct type Dog) as Animal valueEmbedding is not inheritance.Pass d.Animal or use an interface.
Inner method ignores the outer overrideThe inner method calls its own version.Pass behaviour in with an interface.

The last row surprises people who know Java. Inside Animal, methods only see Animal, never the outer Dog. Embedding questions are common in interviews too, so practise with my Go interview questions and answers.

Official Resources

These pages come straight from the Go team, so they stay accurate and up to date.

Quick Recap

  • Go struct embedding places a type inside a struct without a field name.
  • Fields and methods of the inner type are promoted to the outer one.
  • An outer method with the same name overrides the inner one.
  • Promoted methods help the outer struct satisfy interfaces.
  • Embedding is composition, not inheritance.

What’s Next?

You can now build bigger types from small ones. Next, we will return to concurrency and wait on many channels at once with the select statement.

Next lesson: Go Select Statement Explained with Examples