Basic embedding
How embedding works
Field promotion
Fields from the embedded struct are “promoted” to the outer struct. You can access them directly:
Embedding vs composition
- Embedding
- Regular field
Interface embedding
Interfaces can also be embedded to compose larger interfaces:Common use cases
Adding behavior
Extend a base type with additional fields and methods
Interface composition
Build complex interfaces from smaller ones
Mixins
Share common functionality across types
Decorator pattern
Wrap types to add functionality
Example: Multiple embeddings
Naming conflicts
Best practices
Prefer composition over inheritance
Prefer composition over inheritance
Go’s embedding provides a form of composition. Favor small, focused types that you compose together rather than large hierarchies.
Use embedding for interface satisfaction
Use embedding for interface satisfaction
Embedding is particularly useful when you want to satisfy an interface by reusing an existing implementation.
Be explicit when needed
Be explicit when needed
While promoted fields are convenient, use explicit paths (
co.base.num) when it improves clarity.Document embedding relationships
Document embedding relationships
Make it clear in comments when a type embeds another and why.
Related topics
Structs
Learn about struct basics
Methods
Define methods on types
Interfaces
Interface composition