Go study
Offline — showing the cached copy.
Home / Go / 3. Types, method sets, embedding

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 T contains value-receiver methods; method set of *T contains both.
  • Therefore T may 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
METHOD SETS VALUE RECEIVER in method set o… POINTER RECEIVER only in method … INTERFACE CHECK T fails if it n… EMBEDDING promotes whatev…
Method sets

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?