Go builds complex data structures by composing simpler types: structs hold other structs, slices, maps and pointers as fields, and struct embedding promotes an inner type's fields and methods to the outer type. There is no inheritance, so you assemble behavior from small, focused types and connect them through interfaces.
This article walks through nested structs, embedding, collections of composed types, composition with interfaces, and a few design rules that keep composed types easy to maintain.
The simplest composition is a named field of another struct type. Each type stays small and testable on its own.
Because Address is a normal field, access goes through c.Address. Nothing is promoted, which keeps the outer API explicit.
When you want the inner fields and methods available directly, embed the type by leaving out the field name.
Embedding is composition, not inheritance. Employee is not a Person, and Describe receives the embedded Person. If you define Describe on Employee, it shadows the promoted method.
The standard encoding/json package flattens embedded structs into the parent object unless the embedded field has a tag. This makes embedding handy for shared fields such as audit data.
Marshalling an Order gives one flat object with id, total, created_at and updated_at.
Slices, maps and pointers let composed types model one-to-many relationships and trees.
Use pointers for recursive types and for values that must be shared or are large. For types that must not be copied, such as those containing a sync.Mutex, use pointer receivers and pass them by pointer.
Compose behavior by holding an interface-typed field. This lets you swap implementations, for example in tests.
OrderService depends on behavior, not on a concrete type. Passing a fake Notifier in a test needs no mocking framework. Interfaces can also be composed from smaller ones, as io.ReadWriter is built from io.Reader and io.Writer.
It is building a larger type from smaller ones, using struct fields, embedding and interface-typed fields, instead of inheriting from a base class.
An embedded type's fields and methods are promoted to the outer type. A named field requires outer.field.Method() and promotes nothing.
Yes. The struct then has the interface's methods, which delegate to the stored value. It is useful for decorators and partial test doubles, but a nil interface causes a panic when called.
No. Embedding is a compile-time layout with no extra indirection unless you embed a pointer or an interface.
Compose Go types with nested structs, embedding, collections and interface fields. Choose embedding when you want promoted methods, a named field when you want an explicit API, and interfaces when you need swappable behavior. The result is flat, testable and easy to evolve.