Skip to content
Tutorials Center
My learning

Topics

Lesson 44 of 147 ยท Structs and Methods

Struct Embedding and Composition

Learn Go struct embedding - promoted fields and methods, shadowing, embedding interfaces and pointers, initializing embedded types, and composition over inheritance.

Go has no classes and no inheritance. When you want one type to reuse the fields and behavior of another, you use composition: you put one struct inside another. Go adds a small piece of syntax to make this pleasant, called embedding. If you list a type in a struct without giving it a field name, its fields and methods are promoted to the outer type, so you can use them as if they were the outer type's own.

Embedding looks a lot like inheritance, and newcomers often treat it that way. It is not. The embedded value is a real, separate value inside the struct, the outer type never "is a" version of it, and there is no virtual dispatch. This lesson shows how promotion works, what happens when names collide, how to embed interfaces and pointers, how to initialize embedded types, and why Go programmers say "composition over inheritance". It builds on Structs and Methods.

Has-a with a named field

Before embedding, here is plain composition with a named field. A Car has an Engine:

Go Composition with a named field

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.

This is already good design. The cost is verbosity: every use goes through car.Engine. Embedding removes that step.

Embedding: promoted fields and methods

To embed a type, write just the type name in the struct, with no field name. The field's name is the type's name:

Go Embedding promotes fields and methods

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.

car.Horsepower is shorthand for car.Engine.Horsepower, and car.Describe() for car.Engine.Describe(). When Go sees a selector like car.X, it looks in Car first, then in embedded types, one level deeper at a time. The printed form {Name:Roadster Engine:{Horsepower:300}} proves the embedded struct is still just a field called Engine.

Promotion is only a convenience for selectors. The receiver of Describe is still the Engine, not the Car. The method has no idea it was called through a car.

Initializing embedded fields in literals

The embedded field is named after its type, so the classic way to fill it in a composite literal is to use that name as the key:

Go Initializing embedded types

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.

e.City reaches through Person and Address. In the literal, the keys are Person: and Address:, the type names. Go 1.27 also accepts promoted fields as keys, so Employee{Name: "Mira", Title: "Engineer"} compiles and fills Person.Name for you (earlier releases rejected it with an error about promoted fields). That shortcut has a limit: it does not work through an embedded pointer: using a promoted field of an embedded *Logger as a key fails with invalid implicit pointer indirection to reach P, because Go would have to allocate the pointer for you. Whichever style you choose, the nested form is clearer and works in every version.

Shadowing: the outer name wins

If the outer type declares a field or method with the same name as a promoted one, the outer name shadows the promoted one. The embedded one is still reachable through its full path:

Go Shadowing a promoted method

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.

The last line is the key difference from inheritance in Java or Python. d.Intro() runs Animal.Intro, whose receiver is an Animal, so the call to a.Speak() inside it is Animal.Speak, not Dog.Speak. There is no virtual dispatch through embedding. If you want an overridable behavior, use an interface, as shown later in this lesson.

Ambiguous selectors

If two embedded types at the same depth both have a field or method with the same name, a selector using that name is ambiguous. Go reports an error, but only when you actually use the ambiguous name:

Go Ambiguous selector (fails on purpose)

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.

The compiler says ambiguous selector f.Name. Declaring File itself is fine, and qualified selectors still work. A shallower name always wins over a deeper one, so only equal-depth collisions are a problem.

Embedding pointers

You can embed a pointer type, *Engine. The outer struct then holds a pointer, so several outer values can share one embedded value, and the embedded pointer can be nil:

Go Embedding a pointer type

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.

Because both s and w embed the same *Logger, the counter is shared: the three messages are numbered 1, 2 and 3. If you forget to set the pointer, calling a promoted method that touches l.count panics with a nil pointer dereference, so constructors should always fill embedded pointers (see Constructors, Options and Builders).

Embedding and method sets

Promotion changes method sets in a predictable way. For a struct S that embeds T:

Outer type Gets methods of T with receiver
S (embeds T) T only
*S (embeds T) T and *T
S or *S (embeds *T) T and *T

So embedding a pointer *T gives even the plain value S access to the pointer-receiver methods of T. That is another reason loggers and mutex-carrying helpers are often embedded as pointers. The rules behind this table are in Value vs Pointer Receivers.

Embedding interfaces

You can also embed an interface in a struct. The struct then satisfies that interface automatically, with the embedded value forwarding the calls. This is a powerful way to wrap or partially override behavior. Here a LoudSpeaker decorates any Speaker and changes only one method:

Go Embedding an interface to decorate behavior

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.

LoudSpeaker never wrote a Name method; it comes from the embedded interface. The standard library uses this trick often, for example to wrap an http.ResponseWriter and intercept only WriteHeader. One danger: if the embedded interface is nil, calling a promoted method panics, so always set it.

Interfaces can also embed other interfaces to build bigger ones, such as io.ReadWriter combining io.Reader and io.Writer. That is covered in Interfaces.

Composition over inheritance

Embedding gives you reuse without a type hierarchy:

  • Has-a, not is-a. A Car has an Engine. A Dog embedding Animal does not make a Dog an Animal: you can't pass a Dog to a function that takes an Animal.
  • Polymorphism comes from interfaces. Both Dog and Cat can satisfy a Speaker interface, and functions accept the interface.
  • No fragile base class. Changing Animal can't silently change Dog's overridden behavior, because Animal never calls Dog's methods.

The following program shows all three: Dog is not an Animal, but both are Speakers through methods:

Go Interfaces, not embedding, give polymorphism

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.

The comment about describeAnimal(d) is true: the compiler would reject it with cannot use d (variable of struct type Dog) as Animal value in argument. You pass d.Animal explicitly instead.

Embed when you want the outer type to expose the embedded type's API. Use a named field when you only want to use it internally. Embedding exports the embedded type's methods from your type's public surface, which becomes part of your API.

Common mistakes

  • Expecting overrides to be virtual. Methods defined on the embedded type always see the embedded type as their receiver.
  • Embedding just to save typing. Promoted methods become part of your API. If you embed a sync.Mutex, Lock and Unlock become public methods of your type; a named field mu sync.Mutex keeps them private.
  • Forgetting to initialize embedded pointers or interfaces. They default to nil.
  • JSON surprises. Embedded struct fields are flattened into the parent object by encoding/json, which is often wanted but worth knowing (see Struct Tags).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Given type Car struct { Engine } where Engine has a field Horsepower, what does car.Horsepower mean?

    Embedded fields and methods are promoted, so the selector car.Horsepower is rewritten to go through the embedded Engine.
  2. 2. Dog embeds Animal. Both have a method Speak, and Animal has Intro() that calls a.Speak(). What does dog.Intro() call?

    Embedding does not provide virtual dispatch. Intro has an Animal receiver, so it calls Animal.Speak.
  3. 3. Two embedded types at the same depth both define Name(). When does the compiler complain?

    Declaring the struct is legal. Using the ambiguous name reports ambiguous selector, and qualified names such as f.Reader.Name() still work.
  4. 4. How do you set the embedded Person field in a literal of type Employee struct { Person; Title string }?

    The field name of an embedded type is the type name, so the literal uses the key Person:. A dotted path such as Person.Name is never valid as a key.
  5. 5. What happens if a struct embeds an interface value that is nil and you call a promoted method?

    A nil interface has no dynamic type or method table, so calling a method on it panics at run time.

Summary

  • Embedding means declaring a field with only a type; its fields and methods are promoted to the outer type.
  • The embedded value is a real field named after its type, and you must use that name in composite literals.
  • Outer names shadow promoted ones, and equal-depth name clashes are ambiguous only when used.
  • There is no virtual dispatch: methods of the embedded type see only the embedded type.
  • You can embed pointers (shared, may be nil) and interfaces (decorate and override part of a behavior).
  • Prefer composition and interfaces to hierarchies; embed when you want to expose the inner API.

Next: Constructors, Options and Builders