Embedding
Embed types to compose behavior or promote fields deliberately, not to simulate inheritance.
Canonical guidance
- use embedding to compose behavior carefully
- understand that promoted methods become part of the outer type’s method set
- prefer explicit named fields when the relationship is not meant to be promoted
Use when
- composing helper behavior
- small wrappers around existing types
- deliberate method promotion
Avoid
- treating embedding as inheritance
- exporting promoted APIs accidentally
- deep chains of embedded types
Preferred pattern
type MetricsServer struct {
*http.Server
Log *slog.Logger
}
Anti-pattern
- embedding many unrelated types into one aggregate “base class”
Explanation: This anti-pattern is tempting because it looks concise, but it hides which behavior is truly owned by the outer type.
Why
- embedding changes method sets and API shape, not just field layout
Related pages
Sources
- The Go Programming Language Specification - Go Team
- Effective Go - Go Team