3. Types, method sets, embedding
One-liner. Go has no inheritance — it has composition plus an exact method-set rule.
Memorize
- Defined type (
type UserID int) is a new type; alias (type A = B) is the same type. - Method set of
Tcontains value-receiver methods; method set of*Tcontains both. - Therefore
Tmay not satisfy an interface that needs a pointer-receiver method. - Embedding promotes fields and methods; it is not subtyping — no virtual dispatch.
- An embedded pointer shares state; an embedded value is copied.
- Comparable types can be map keys; slices, maps and funcs are not comparable.
- Struct field order affects size (padding). Reorder large→small to shrink memory.
type Logger struct{ prefix string }
func (l *Logger) Log(s string) { fmt.Println(l.prefix, s) }
type Service struct{ *Logger } // promoted, shares the pointer
var _ interface{ Log(string) } = Service{} // ok: *Logger method promoted
Trap. Storing a large struct by value in a map or slice and copying it on every method call. Do this. Use pointer receivers when the type is big or must be mutable; be consistent.
Check
func (s *Svc) Start() exists, and var _ Starter = Svc{} is checked at compile time. What happens?
Why
Auto-addressing works for addressable values on a call, but interface satisfaction is decided on the static type's method set.