SyntaxPilot
Courses/Go Programming/Lesson 23

Go Programming · Lesson 23 of 89 · 11 min

Embedding and composition

struct embeddingpromoted fields and methodsembedding pointer typesembedding interfaces in structsname conflicts and shadowingcomposition over inheritanceno inheritance in Godecorating behaviour via embedding

These are the notes for Go episode 23. Raju's Bill works well: it holds item prices and has a Total() method, so it satisfies the Totaler interface from episode 21. Now he wants a table bill: everything a Bill has, plus a table number. Languages like Java and Python would say "make a subclass". Go has no inheritance, no extends keyword. So, starting from the obvious attempts and their problems, you will invent Go's answer: struct embedding and the idea behind it, composition. You will learn what an embedded field is, how fields and methods get promoted to the outer type, why promoted methods count for interfaces, why embedding is not inheritance (has-a, not is-a; no virtual methods), the depth rule behind shadowing and ambiguous selectors, embedding pointer types (sharing, and the nil danger), embedding interfaces in structs to decorate any value with extra behaviour, and the principle of composition over inheritance. The expert corner covers method sets with embedded T vs *T, multi-level depth, embedding sync.Mutex, how sort.Reverse replaces one method of an interface, the fmt.Stringer promotion surprise, JSON and embedded fields, and what the compiler generates behind a promoted method. Every example runs as-is in the SyntaxPilot compiler (language: Go); outputs, compiler errors and panics are from real runs of go run main.go (Go 1.24, linux/amd64). Panic traces show /tmp/.../main.go where the real temporary folder was; the pc=, +0x... and 0xc... numbers (and the Go install path) differ between machines and runs.

Words you need first

A few words from earlier episodes, in one place:

  • A struct is a type that groups named values together (episode 19). Each named value is a field: type Bill struct{ Items []float64 } has one field, Items.
  • A method is a function attached to a type, with a receiver written before its name (episode 20): func (b Bill) Total() float64. A value receiver (b Bill) works on a copy; a pointer receiver (b *Bill) works on the original.
  • The method set of a type is the list of methods that a value of that type has for interfaces (episode 20, 21). A type satisfies an interface when its method set contains every method the interface lists.
  • A selector is the x.f form you use to reach a field or a method: in t.Items and t.Total(), .Items and .Total are selectors.
  • Inheritance (in Java, C++, Python, C#) is when a new class, the subclass or child class, is declared as a special kind of an existing class, the parent class or base class (class TableBill extends Bill). The child automatically gets the parent's fields and methods, and is a parent everywhere: you can pass a TableBill where a Bill is expected.

The problem: reuse Bill

In this episode Bill holds a slice of item prices, Items []float64, and has a value-receiver method Total() float64 that adds them up; Totaler is episode 21's interface{ Total() float64 }. Their full code is in the first program below.

Raju needs a TableBill: the same items and the same Total, plus Table int. Two obvious attempts.

Attempt one: copy-paste

Copy Bill's fields and its Total method into a new type (the left side of the video's compare slide):

type TableBill struct {
    Items []float64
    Table int
}

// Total copied from Bill...
func (t TableBill) Total() float64 {
    var s float64
    for _, p := range t.Items {
        s += p
    }
    return s
}
  • It works today: in a real run next to Bill, fmt.Println(b.Total(), t.Total(), t.Table) for Bill{[]float64{10, 15}} and TableBill{[]float64{10, 15}, 4} printed 25 25 4.
  • But next month Raju fixes a rounding bug in Bill.Total, and forgets the copy. Now there are two versions of the same code, slowly drifting apart. Every new kind of bill (a parcel bill, a delivery bill) adds another copy. Programmers call this duplicate code, and the rule against it is often written DRY: "Don't Repeat Yourself".

Attempt two: a named field

No copying: put a whole Bill inside, as an ordinary field named B, and reach it through t.B:

type TableBill struct {
    B     Bill
    Table int
}

t.B.Items
t.B.Total()

The full program: build a TableBill, print through t.B, then try to use it as a Totaler:

package main

import "fmt"

type Totaler interface{ Total() float64 }

type Bill struct {
    Items []float64
}

func (b Bill) Total() float64 {
    var s float64
    for _, p := range b.Items {
        s += p
    }
    return s
}

type TableBill struct {
    B     Bill
    Table int
}

func main() {
    t := TableBill{B: Bill{[]float64{10, 15}}, Table: 4}
    fmt.Println(t.B.Items, t.B.Total())

    var x Totaler = t
    fmt.Println(x.Total())
}
# command-line-arguments
./main.go:28:21: cannot use t (variable of struct type TableBill) as Totaler value in variable declaration: TableBill does not implement Totaler (missing method Total)
  • TableBill does not implement Totaler (missing method Total). The Total method belongs to the field B, not to TableBill. A struct's method set contains only the methods declared on that struct type; methods of its named fields are not included.
  • So every caller has to write t.B.Items and t.B.Total(), and a TableBill can't go where a Totaler is expected. Calling t.Total() directly fails too (real run): t.Total undefined (type TableBill has no field or method Total).
  • What we really want: put a Bill inside, and have its fields and methods show up on TableBill itself.

Struct embedding: a laptop with a built-in webcam

Think of a laptop with a built-in webcam.

A laptop In Go Name
The webcam is built in: no cable, no separate name struct{ Bill; Table int } an embedded field: a field with only a type
You press "take photo" on the laptop; the webcam does the work t.Total() → t.Bill.Total() a promoted method
It's still a laptop, not a webcam TableBill is not a Bill not inheritance: has-a, not is-a
  • An embedded field is a struct field written with only a type and no field name. Putting one in a struct is called struct embedding (or just embedding). The type you embed is the embedded type; the struct that contains it is the outer type (or embedding type).
  • The embedded field still has a name: the type's name (without the package or the *). Embedding Bill creates a field called Bill; embedding io.Writer creates a field called Writer.
  • The fields and methods of the embedded type are promoted: you can use them directly on the outer value, as if they were declared there. t.Items is short for t.Bill.Items, and t.Total() is short for t.Bill.Total(). The compiler fills in the missing .Bill for you; the work is still done by the inner Bill.

Inside TableBill, just the word Bill, with no field name. We also give *Bill an Add method (pointer receiver, because it changes the bill). Then t.Add, t.Items and t.Total, all on the TableBill:

package main

import "fmt"

type Totaler interface{ Total() float64 }

type Bill struct {
    Items []float64
}

func (b Bill) Total() float64 {
    var s float64
    for _, p := range b.Items {
        s += p
    }
    return s
}

func (b *Bill) Add(p float64) { b.Items = append(b.Items, p) }

type TableBill struct {
    Bill  // embedded: no field name
    Table int
}

func main() {
    t := TableBill{Bill: Bill{[]float64{10}}, Table: 4}
    t.Add(15) // promoted from Bill
    fmt.Println(t.Table, t.Items, t.Total())

    var x Totaler = t
    fmt.Printf("%+v %.0f\n", t, x.Total())
}
4 [10 15] 25
{Bill:{Items:[10 15]} Table:4} 25
  • Table 4, items 10 and 15, total 25. t.Add(15) is a promoted method: it ran Bill's Add on the Bill inside t.
  • With no extra code, TableBill now satisfies Totaler: var x Totaler = t compiled. Promoted methods join the outer type's method set, so they count for interfaces. You just invented embedding.
  • %+v (print a struct with field names, episode 18) shows the truth: {Bill:{Items:[10 15]} Table:4}. The embedded field is still there, and its name is Bill. You can always write the full path t.Bill.Items; t.Items is a shortcut.
  • t.Add(15) worked even though Add has a pointer receiver, because t is addressable (a variable has an address in memory), so Go took &t.Bill for you, exactly as in episode 20.
  • In a struct literal you fill the embedded field by its type name: TableBill{Bill: Bill{...}, Table: 4}, or by position: TableBill{Bill{...}, 4}.

Promoted fields can't be used as field names in a literal. This fails (real run):

package main

import "fmt"

type Bill struct{ Items []float64 }

type TableBill struct {
    Bill
    Table int
}

func main() {
    t := TableBill{Items: []float64{10}, Table: 4}
    fmt.Println(t)
}
# command-line-arguments
./main.go:13:20: unknown field Items in struct literal of type TableBill

The Go spec (the official language definition) says promoted fields act like ordinary fields except in composite literals (the T{...} syntax that builds a struct, slice or map value). Write TableBill{Bill: Bill{Items: []float64{10}}, Table: 4}.

Embedding is not inheritance

In Java, a subclass is its parent: a TableBill would be a Bill, usable anywhere a Bill is. Test that in Go: assign a TableBill to a variable of type Bill.

package main

import "fmt"

type Bill struct{ Sum float64 }

type TableBill struct {
    Bill
    Table int
}

func main() {
    t := TableBill{Bill{25}, 4}
    var b Bill = t
    fmt.Println(b)
}
# command-line-arguments
./main.go:14:18: cannot use t (variable of struct type TableBill) as Bill value in variable declaration
  • cannot use t (variable of struct type TableBill) as Bill value. Go never converts one struct type into another.
  • This is the difference between has-a and is-a. Is-a is the inheritance relationship: "a TableBill is a Bill". Has-a is the composition relationship: "a TableBill has a Bill inside it". Embedding is always has-a.
  • To pass the inner bill, say so: var b Bill = t.Bill. That compiles and gives you a copy of the inner Bill.
  • The Go FAQ answers "Is Go an object-oriented language?" with "Yes and no": Go has types and methods, but no type hierarchy (no tree of parent and child types); embedding gives something analogous, but not identical, to subclassing.

No virtual methods: the override trap

The bigger surprise. Bill has Total and a Print method that calls b.Total(). TableBill adds a 10-rupee service charge by declaring its own Total. Then we call t.Print(), which was promoted from Bill. Will it use the new Total?

package main

import "fmt"

type Bill struct{ Sum float64 }

func (b Bill) Total() float64 { return b.Sum }
func (b Bill) Print() {
    fmt.Println("Total:", b.Total())
}

type TableBill struct {
    Bill
    Service float64
}

// TableBill's own Total shadows Bill's
func (t TableBill) Total() float64 {
    return t.Bill.Total() + t.Service
}

func main() {
    t := TableBill{Bill{100}, 10}
    fmt.Println(t.Total(), t.Bill.Total())
    t.Print() // Bill's Print: which Total?
}
110 100
Total: 100
  • t.Total() is 110: TableBill's own Total. t.Bill.Total() is 100: Bill's.
  • TableBill's Total shadows (hides) the promoted one: when the outer type declares a name that the embedded type also has, the outer one wins (the depth rule, next section). Inside it, t.Bill.Total() still reaches Bill's version, which is how the new method reuses the old one.
  • But Print printed Total: 100, not 110! A promoted method runs on the inner value. t.Print() is really t.Bill.Print(), and inside Print, b is just a Bill that has never heard of TableBill. So b.Total() is Bill's Total.
  • In Java this would print 110. When a subclass declares a method with the same name and signature as its parent's, it overrides it (replaces it for objects of the subclass), and Java methods are virtual: a virtual method call looks up, at run time, the version that belongs to the real object, even when the call is written inside the parent's code. Choosing the method at run time is called dynamic dispatch (episode 21).
  • Go has no virtual methods on structs. Inner code always calls inner methods. Code in Bill can never "call down" into TableBill.

The Go fix is an interface (episode 21), because interfaces are how Go chooses behaviour at run time. Make Print a function that takes a Totaler (with type Totaler interface{ Total() float64 }, and Bill, TableBill and both Total methods as above; the Bill.Print method is gone):

func Print(t Totaler) {
    fmt.Println("Total:", t.Total())
}

func main() {
    t := TableBill{Bill{100}, 10}
    Print(t)      // TableBill's Total
    Print(t.Bill) // Bill's Total
}
Total: 110
Total: 100

Print(t) gets TableBill's Total; Print(t.Bill) gets Bill's. Embedding reuses code; interfaces choose behaviour.

Shadowing and conflicts: which name wins?

Think of shouting "Raju!" in a house.

A house with two Rajus In Go Name
The Raju in this room answers first the outer type's own Total the shallowest depth wins
The Raju upstairs answers only if you say "upstairs Raju" t.Bill.Total() shadowing: hidden, still reachable
Two Rajus in the same room: "which one?" two Name fields at depth 1 ambiguous selector

The rule is depth: how many embedded fields you go through to reach a name.

  • The outer type's own fields and methods (TableBill's Table and Total) are at depth 0.
  • The embedded Bill's fields and methods (Items, Total, Print) are at depth 1. A type embedded inside Bill would be at depth 2, and so on.
  • When a selector like t.Total matches names at several depths, the shallowest one wins. The deeper one is shadowed: hidden from the short form, but still there through the full path t.Bill.Total(). (Episode 3 used "shadowing" for an inner variable hiding an outer one; it's the same idea.)
  • If two names are at the same shallowest depth, Go refuses to guess.

An Order embeds a Customer and a Waiter. Both have a Name field, both at depth 1:

package main

import "fmt"

type Customer struct{ Name string }
type Waiter struct{ Name string }

type Order struct {
    Customer
    Waiter
    Table int
}

func main() {
    o := Order{Customer{"Asha"}, Waiter{"Ravi"}, 4}
    fmt.Println(o.Customer.Name, o.Waiter.Name)
    fmt.Println(o.Name)
}
# command-line-arguments
./main.go:17:19: ambiguous selector o.Name
  • ambiguous selector o.Name: an ambiguous selector is one that matches more than one field or method at the same depth, so the compiler can't tell which you mean. Customer's or Waiter's?
  • It's only an error when you use the name. Declaring the struct was fine, and the full paths o.Customer.Name and o.Waiter.Name work. Only line 17 was reported.
  • Fix it by naming the path, or by giving Order its own Name at depth 0, which beats both. Real run with Name string added to Order after Waiter, o := Order{Customer{"Asha"}, Waiter{"Ravi"}, "Order #7", 4} and the same two prints:
Order #7
Asha Ravi

The same rule applies to methods, and an ambiguous method is not in the method set at all, so the type no longer satisfies an interface that needs it (practice 5 shows the message).

Embedding pointer types: one bill, many seats

You can also embed a pointer to a struct type: *Bill. The field's name is still Bill.

A family dinner In Go Name
Two seats, one shared bill for the family two Seats holding the same *Bill an embedded pointer: shared data
Each seat adds its order to that one bill s1.Add(40), s2.Add(25) promoted methods through the pointer
An empty seat with no bill attached var s3 Seat → Bill is nil a nil embedded pointer panics

Seat embeds *Bill. A family sits at two seats sharing one bill: both seats hold the same pointer. Seat 1 adds 40, seat 2 adds 25. Then a zero Seat, whose pointer is nil:

package main

import "fmt"

type Bill struct{ Sum float64 }

func (b *Bill) Add(p float64) { b.Sum += p }

type Seat struct {
    *Bill // embedded pointer
    No    int
}

func main() {
    family := &Bill{}
    s1 := Seat{family, 1}
    s2 := Seat{family, 2}
    s1.Add(40)
    s2.Add(25)
    fmt.Println(family.Sum, s1.Sum, s2.Sum)

    var s3 Seat // Bill pointer is nil
    fmt.Println(s3.No)
    fmt.Println(s3.Sum)
}
65 65 65
0
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x491be2]

goroutine 1 [running]:
main.main()
    /tmp/.../main.go:24 +0x102
exit status 2
  • 65 65 65: one shared bill, seen through family and both seats. Each Seat holds only a copy of the pointer (an address), so they all point to the same Bill.
  • s3.No printed 0: the zero value of a struct sets every field to its zero value, and the zero value of a pointer is nil.
  • s3.Sum panics: invalid memory address or nil pointer dereference. s3.Sum is really s3.Bill.Sum, and s3.Bill is nil; dereferencing a pointer means following it to the value it points to, which is impossible when it points nowhere (episode 11). A panic is a run-time crash that stops the program (episode 26). It compiled fine: the compiler can't know the pointer will be nil.

Rule: embed a value (Bill) when each outer value should own its own copy; embed a pointer (*Bill) when several outer values should share one, and always fill it in (Seat{&Bill{}, 1}, or a constructor function NewSeat, episode 20).

The spec also limits what can be embedded: a type name T, or a pointer *T where T is a type name that is not an interface and not itself a pointer. Real errors for the wrong ones, from a file declaring type Bad1 struct{ Bill; Bill } (lines 10-13) and type Bad2 struct{ *io.Writer } (lines 15-17):

# command-line-arguments
./main.go:12:5: Bill redeclared
    ./main.go:11:5: other declaration of Bill
./main.go:16:5: embedded field type cannot be a pointer to an interface
  • Embedding the same type twice makes two fields with the same name: Bill redeclared. struct{ Bill; *Bill } fails the same way, because both fields are named Bill.
  • *io.Writer is a pointer to an interface: not allowed (and almost never what you want; an interface can already hold a pointer, episode 21). **Bill isn't even valid syntax: syntax error: unexpected *, expected name.

Embedding interfaces in structs: a water meter on a pipe

A struct can embed an interface type too. Think of fitting a water meter on a pipe.

Plumbing In Go Name
Any pipe: to a tank, a garden, a sink struct{ io.Writer; N int } an embedded interface: wrap any writer
A meter fitted in between counts every litre its own Write: c.N += len(p) adding behaviour
The water flows on; the pipe still works c.Writer.Write(p) delegation
  • io.Writer (episode 22) is the standard interface interface{ Write(p []byte) (n int, err error) }: anything you can write bytes to. os.Stdout (the terminal), a *strings.Builder (a growing string in memory), a file and a network connection are all io.Writers. fmt.Fprintln(w, ...) prints a line to any io.Writer w.
  • The embedded field io.Writer (named Writer) can hold any writer. Its method Write is promoted, so the outer struct is an io.Writer too.
  • Delegation means passing a call on to another value to do the real work. A method that only delegates is often called a forwarding method; embedding writes those forwarding calls for you.
  • Wrapping a value in another value that has the same interface but adds behaviour (counting, logging, timing, uppercasing...) is the decorator pattern. The wrapper is the decorator: callers can't tell it from the original, so it plugs in anywhere.

A CountingWriter decorates any io.Writer

CountingWriter embeds io.Writer and adds N. Its own Write adds len(p) to N, then calls c.Writer.Write(p). receipt from episode 22 takes any io.Writer. We wrap the terminal, then a strings.Builder:

package main

import (
    "fmt"
    "io"
    "os"
    "strings"
)

type CountingWriter struct {
    io.Writer // any writer, embedded
    N         int
}

func (c *CountingWriter) Write(p []byte) (int, error) {
    c.N += len(p)
    return c.Writer.Write(p)
}

func receipt(w io.Writer) {
    fmt.Fprintln(w, "chai    10.00")
    fmt.Fprintln(w, "samosa  15.00")
}

func main() {
    cw := &CountingWriter{Writer: os.Stdout}
    receipt(cw)
    fmt.Println("bytes written:", cw.N)
    var sb strings.Builder
    cw2 := &CountingWriter{Writer: &sb}
    receipt(cw2)
    fmt.Println(cw2.N, len(sb.String()))
}
chai    10.00
samosa  15.00
bytes written: 28
28 28
  • The receipt still reaches the screen, and bytes written: 28: two lines of 14 bytes each (13 characters plus the newline \n).
  • With the builder, 28 28: the count matches exactly what landed inside. receipt never changed. We added behaviour from outside, by wrapping.
  • CountingWriter's own Write (depth 0) shadows the promoted Write of the embedded interface (depth 1), and calls it explicitly as c.Writer.Write(p). Same shadowing rule as TableBill.Total.
  • Write has a pointer receiver because it changes c.N, so we pass cw (a *CountingWriter).

The danger: a nil embedded interface

A zero CountingWriter has a nil interface inside (the zero value of an interface is nil, episode 21):

package main

import (
    "fmt"
    "io"
)

type CountingWriter struct {
    io.Writer
    N int
}

func main() {
    var cw CountingWriter // Writer is nil
    fmt.Fprintln(cw, "hello")
}
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x18 pc=0x490ae3]

goroutine 1 [running]:
main.(*CountingWriter).Write(0xc0001201a0?, {0xc000102040?, 0x1?, 0x40f585?})
    <autogenerated>:1 +0x23
fmt.Fprintln({0x4d8c38, 0xc000122000}, {0xc00010af18, 0x1, 0x1})
    /usr/local/go1.24.7/src/fmt/print.go:305 +0x6f
main.main()
    /tmp/.../main.go:15 +0x65
exit status 2
  • It compiles, because Write was promoted from the interface: as far as the compiler knows, CountingWriter is an io.Writer. (This CountingWriter has no Write of its own, so the value cw works too.)
  • At run time fmt.Fprintln calls cw.Write, which forwards to cw.Writer.Write, and there is no real writer to call: nil pointer dereference. Look at the trace: main.(*CountingWriter).Write at <autogenerated>:1. That is the forwarding method the compiler generated for the promoted method (see the expert corner).
  • Always set the embedded interface, for example CountingWriter{Writer: os.Stdout}.

Composition over inheritance

Step back and compare the two ways to reuse code.

Building a meal In Go Name
A thali: separate small dishes put together on one plate struct{ Order; Table int } composition: build from parts
Each dish is still itself and can go on another plate Order reused by TableOrder and Parcel reuse without a family tree
Swap a dish without touching the others change one part; others don't care no fragile base class
  • Composition means building bigger types out of smaller parts that each do one job: a TableBill has a Bill. Inheritance builds a class hierarchy: a tree where each child is a special kind of its parent.
  • Embedding is composition plus automatic forwarding: the compiler promotes the parts' fields and methods so you don't write forwarding methods by hand.
  • Interfaces do the other job inheritance did: choosing behaviour at run time (the Java "override").
  • Composition over inheritance is a long-standing design principle (the classic book Design Patterns advises "favor object composition over class inheritance"): prefer combining small parts to building deep class trees.
  • No inheritance in Go: no extends, no class, no subclasses, no type hierarchy. Go only does composition.
  • The payoff: no deep chains of parent classes where changing one base class silently breaks dozens of children. That is the fragile base class problem: a base class is "fragile" when an innocent-looking change inside it (say, Print starts calling a different method) changes the behaviour of every subclass that overrides something, because the subclasses depend on the base class's private details. In Go, Bill's code only ever calls Bill's methods, so changing Bill can't secretly route through TableBill.

Expert corner

Method sets with embedded T vs *T

Promoted methods join the outer method set, but which ones? The spec's rule, for a struct type S:

S embeds Method set of S (a value) gets Method set of *S (a pointer) gets
T T's value-receiver methods value- and pointer-receiver methods of T
*T value- and pointer-receiver methods of T value- and pointer-receiver methods of T

Bill's Add has a pointer receiver. ByValue embeds Bill; ByPointer embeds *Bill:

package main

import "fmt"

type Adder interface{ Add(p float64) }

type Bill struct{ Sum float64 }

func (b *Bill) Add(p float64) { b.Sum += p }

type ByValue struct{ Bill }    // embeds Bill
type ByPointer struct{ *Bill } // embeds *Bill

func main() {
    var a Adder

    v := ByValue{}
    a = &v // *ByValue: has (*Bill).Add
    a.Add(10)
    fmt.Println(v.Sum)

    p := ByPointer{&Bill{}}
    a = p // the value ByPointer already holds a *Bill
    a.Add(20)
    fmt.Println(p.Sum)
}
10
20
  • &v (a *ByValue) satisfies Adder: through the pointer, Go can reach &v.Bill. Add changed v itself, so v.Sum is 10.
  • The value p satisfies Adder: it already contains a *Bill, so the pointer method needs nothing more. Copies of p all share the same Bill.

Now add a = v (the value ByValue) before the closing brace (line 27):

# command-line-arguments
./main.go:27:9: cannot use v (variable of struct type ByValue) as Adder value in assignment: ByValue does not implement Adder (method Add has pointer receiver)

The same message as a plain Khata in episode 21: an interface stores a copy of v, and Go can't take the address of the Bill inside that copy.

Depth with more than one level

Depth counts every embedded field on the way. Person embeds Address, and Order embeds Person and Shop:

package main

import "fmt"

type Address struct{ City string }

type Person struct {
    Name string
    Address // City is at depth 1 inside Person
}

type Shop struct{ City string }

type Order struct {
    Person // Name at depth 1, City at depth 2
    Shop   // City at depth 1
}

func main() {
    o := Order{Person{"Asha", Address{"Pune"}}, Shop{"Mumbai"}}
    fmt.Println(o.Name)             // depth 1
    fmt.Println(o.City)             // depth 1 (Shop) beats depth 2 (Address)
    fmt.Println(o.Person.City)      // depth 1 inside Person
    fmt.Println(o.Person.Address.City)
}
Asha
Mumbai
Pune
Pune
  • o.Name is at depth 1 (inside Person).
  • o.City matches Shop.City at depth 1 and Person.Address.City at depth 2: depth 1 wins, so Mumbai. No ambiguity, because only the shallowest depth is checked for duplicates.
  • o.Person.City starts the search from Person, where City is at depth 1 inside it: Pune.

Embedding sync.Mutex: convenient, but public

A goroutine is a function running concurrently with the rest of the program, started with go f() (episode 43); a sync.Mutex is a lock that lets only one goroutine at a time into a piece of code, with Lock and Unlock, and a sync.WaitGroup waits for a group of goroutines to finish (episode 45). Embedding a mutex is a common pattern:

package main

import (
    "fmt"
    "sync"
)

type Counter struct {
    sync.Mutex // embedded: Lock and Unlock are promoted
    n          map[string]int
}

func (c *Counter) Inc(item string) {
    c.Lock()
    defer c.Unlock()
    c.n[item]++
}

func main() {
    c := &Counter{n: map[string]int{}}
    var wg sync.WaitGroup
    for i := 0; i < 100; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            c.Inc("chai")
        }()
    }
    wg.Wait()
    fmt.Println(c.n["chai"])
    c.Lock() // anyone can lock it from outside, too
    fmt.Println("locked from main")
    c.Unlock()
}
100
locked from main
  • c.Lock() and c.Unlock() are promoted from sync.Mutex. 100 goroutines incremented the count safely: 100.
  • The catch: promoted methods are exported (capitalized), so Lock and Unlock become part of Counter's public API (the set of things other code can call). Any code can lock it from outside, as main just did. Many Go programmers prefer a named, unexported field mu sync.Mutex with c.mu.Lock(), so the lock stays private. Embed only what you want to expose.
  • A mutex must never be copied after use. go vet (Go's built-in checker for suspicious code) catches a Counter passed by value (func show(c Counter)); the program runs and prints 3, but go vet reports (real run):
# example
# [example]
./main.go:13:13: show passes lock by value: example.Counter
./main.go:19:10: call of show copies lock value: example.Counter

Replacing one method of an interface: how sort.Reverse works

sort.Interface has three methods: Len, Less and Swap. A struct that embeds sort.Interface gets all three promoted, and can replace just one:

package main

import (
    "fmt"
    "sort"
)

// reverse embeds sort.Interface: Len and Swap are promoted,
// and only Less is replaced.
type reverse struct {
    sort.Interface
}

func (r reverse) Less(i, j int) bool { return r.Interface.Less(j, i) }

func main() {
    prices := []float64{15, 10, 30, 12.5}
    sort.Sort(reverse{sort.Float64Slice(prices)})
    fmt.Println(prices)

    names := []string{"chai", "samosa", "lassi"}
    sort.Sort(sort.Reverse(sort.StringSlice(names)))
    fmt.Println(names)
}
[30 15 12.5 10]
[samosa lassi chai]
  • reverse declares only Less (with i and j swapped); Len and Swap are promoted from whatever is inside. sort.Float64Slice and sort.StringSlice are standard types that attach those methods to []float64 and []string.
  • The standard library's sort.Reverse is built exactly this way: it returns an unexported struct that embeds sort.Interface and overrides only Less. Decorating behaviour via embedding, in the standard library.
  • The same trick makes test fakes: a struct that embeds a big interface and implements only the one method a test needs. (A fake or stub is a simple stand-in for a real dependency, episode 41.) Any other method panics, like the nil CountingWriter, because the embedded interface is nil.

The fmt.Stringer promotion surprise

fmt.Stringer (episode 21) is promoted like any method. Give Bill a String method and embed it:

package main

import "fmt"

type Bill struct{ Sum float64 }

func (b Bill) String() string { return fmt.Sprintf("Rs %.2f", b.Sum) }

type TableBill struct {
    Bill
    Table int
}

func main() {
    t := TableBill{Bill{25}, 4}
    fmt.Println(t) // where did Table go?
    fmt.Printf("%+v\n", t)
}
Rs 25.00
Rs 25.00
  • TableBill satisfies fmt.Stringer through the promoted String, so fmt prints only the bill. The Table field vanished, even with %+v, because fmt uses String() for %v and %+v.
  • This happens with standard types too: in a real run, Event{time.Date(2025, 1, 2, 9, 30, 0, 0, time.UTC), "chai tasting"} (a struct embedding time.Time plus a Name) printed just 2025-01-02 09:30:00 +0000 UTC. Fix: give the outer type its own String (practice 3), or don't embed a type whose String doesn't describe the whole.

JSON flattens embedded structs

encoding/json (episode 35) treats the exported fields of an embedded struct as if they belonged to the outer struct. In real runs, json.Marshal of the video's TableBill{Bill{[]float64{10, 15}}, 4} gave {"Items":[10,15],"Table":4} (no "Bill" key), while a struct with a named field B Bill gave {"B":{"Items":[10,15]},"Table":4}.

What the compiler generates

For each promoted method, the compiler creates a small wrapper (forwarding) method on the outer type, which is why the nil-interface trace showed main.(*CountingWriter).Write at <autogenerated>:1. Conceptually, for TableBill embedding Bill, it is as if you had written:

func (t TableBill) Total() float64 { return t.Bill.Total() }

That generated method is what puts Total in TableBill's method set, and why the receiver inside is always the inner value: there is no hidden link from Bill back to TableBill, so no virtual methods. Promoted fields cost nothing: t.Items compiles to the same memory access as t.Bill.Items, since an embedded value is stored inside the outer struct like any field.

Interface embedding vs struct embedding: episode 22 embedded interfaces in interfaces (interface{ Reader; Writer }: a union of method lists, no values). Today's embedding is in structs: a real field holding a real value (or nil), whose methods are forwarded.

Mini project: TableOrder and Parcel built from Order

An Order holds a map of items to prices and has Total. TableOrder embeds Order and adds a table. Parcel embeds Order, adds a packing charge, and declares its own Total that calls p.Order.Total() plus packing. Both go in one []Totaler:

package main

import "fmt"

type Totaler interface{ Total() float64 }

type Order struct{ Items map[string]float64 }

func (o Order) Total() float64 {
    var s float64
    for _, p := range o.Items {
        s += p
    }
    return s
}

type TableOrder struct{ Order; Table int }
type Parcel struct{ Order; Packing float64 }

func (p Parcel) Total() float64 { return p.Order.Total() + p.Packing }

func main() {
    menu := map[string]float64{"chai": 10, "samosa": 15}
    all := []Totaler{TableOrder{Order{menu}, 4}, Parcel{Order{menu}, 5}}
    for _, t := range all {
        fmt.Printf("%-16T %6.2f\n", t, t.Total())
    }
}
main.TableOrder   25.00
main.Parcel       30.00
  • The two structs are written on one line each to fit the screen (fields separated by ;); gofmt would put each field on its own line. Same types either way.
  • %-16T prints each value's type name, left-aligned in 16 characters (episode 18).
  • TableOrder got Total by promotion: 25. Parcel's own Total shadows it: 25 + 5 = 30.
  • Order's code is written once, reused by both, and the interface picks the right Total for each. Composition plus interfaces: that's Go's whole answer to inheritance.

Extended version: Add and a Discount decorator

Order gets a pointer method Add, which creates the map on first use (writing to a nil map panics, episode 15). A Discount struct embeds the Totaler interface, so it can decorate any totaler, even another type you write tomorrow. Compile-time checks (episode 21) guard every type.

package main

import "fmt"

type Totaler interface{ Total() float64 }

type Order struct{ Items map[string]float64 }

func (o *Order) Add(item string, price float64) {
    if o.Items == nil {
        o.Items = map[string]float64{}
    }
    o.Items[item] += price
}

func (o Order) Total() float64 {
    var s float64
    for _, p := range o.Items {
        s += p
    }
    return s
}

type TableOrder struct {
    Order
    Table int
}

type Parcel struct {
    Order
    Packing float64
}

func (p Parcel) Total() float64 { return p.Order.Total() + p.Packing }

// Discount decorates ANY Totaler: Total is wrapped, nothing else changes.
type Discount struct {
    Totaler
    Percent float64
}

func (d Discount) Total() float64 { return d.Totaler.Total() * (1 - d.Percent/100) }

var (
    _ Totaler = TableOrder{}
    _ Totaler = Parcel{}
    _ Totaler = Discount{}
)

func main() {
    var t TableOrder
    t.Table = 4
    t.Add("chai", 10) // promoted pointer method: Go takes &t.Order
    t.Add("samosa", 15)
    t.Add("chai", 10)

    p := Parcel{Packing: 5}
    p.Add("lassi", 30)

    fmt.Println("table", t.Table, "items", len(t.Items), "chai", t.Items["chai"])
    all := []Totaler{t, p, Discount{t, 10}, Discount{p, 50}}
    for _, x := range all {
        fmt.Printf("%-16T %7.2f\n", x, x.Total())
    }
}
table 4 items 2 chai 20
main.TableOrder    35.00
main.Parcel        35.00
main.Discount      31.50
main.Discount      17.50
  • t.Add("chai", 10) is a promoted pointer method on an addressable variable: Go takes &t.Order. Two chais make 20, and t.Items (a promoted field) has 2 entries.
  • Discount{t, 10} wraps the table order: 35 × 0.9 = 31.50. Discount{p, 50} wraps the parcel: 35 × 0.5 = 17.50. Discount never names TableOrder or Parcel: that's decorating behaviour via embedding.
  • Try it: add a Delivery type that embeds Order with a delivery fee, and wrap it in a Discount without changing anything else.

The next problem: Raju types a dish that isn't on the menu. What should Total (or a price lookup) return? Zero looks like a free meal; minus one looks like a price. Go has a better way to say "something went wrong": next episode, errors, the Go way.

Common mistakes (and the real messages)

You wrote Real error / what happens Fix
struct{ B Bill; Table int } then var x Totaler = t TableBill does not implement Totaler (missing method Total) embed: struct{ Bill; Table int }
named field B Bill, then t.Total() t.Total undefined (type TableBill has no field or method Total) embed, or write t.B.Total()
var b Bill = t cannot use t (variable of struct type TableBill) as Bill value in variable declaration t.Bill (has-a, not is-a)
expecting Bill.Print to call TableBill.Total no error: prints Total: 100, not 110 take an interface: Print(t Totaler)
embed Customer and Waiter, use o.Name ambiguous selector o.Name o.Customer.Name, or a depth-0 Name
both embedded types have Greet(), use Order as Greeter Order does not implement Greeter (ambiguous selector Order.Greet) declare Order.Greet
TableBill{Items: ..., Table: 4} unknown field Items in struct literal of type TableBill TableBill{Bill: Bill{Items: ...}, Table: 4}
var s3 Seat; s3.Sum with *Bill embedded panic: runtime error: invalid memory address or nil pointer dereference set it: Seat{&Bill{}, 1}
var cw CountingWriter; fmt.Fprintln(cw, "hello") panic: ... nil pointer dereference in <autogenerated> CountingWriter{Writer: os.Stdout}
a = v where v embeds Bill, Add has a pointer receiver ByValue does not implement Adder (method Add has pointer receiver) a = &v, or embed *Bill
tables[4].Add(10) on a map[int]TableBill cannot call pointer method Add on TableBill map elements aren't addressable: store *TableBill, or copy, change, put back
struct{ Bill; Bill } or struct{ Bill; *Bill } Bill redeclared embed once, or use named fields
struct{ *io.Writer } embedded field type cannot be a pointer to an interface struct{ io.Writer }
Bill has String(), fmt.Println(tableBill) no error: only the bill prints, Table vanishes give the outer type its own String
embedding sync.Mutex no error: Lock/Unlock become public named field mu sync.Mutex
copying a struct that embeds sync.Mutex runs; go vet: show passes lock by value: example.Counter pass a pointer *Counter

Every message above is from a real run (the code for each appears earlier in these notes, or as a one-liner in the table). The map one, in full (Bill with the pointer method Add, TableBill embedding it, and line 16 tables[4].Add(10) after tables := map[int]TableBill{4: {}}):

# command-line-arguments
./main.go:16:15: cannot call pointer method Add on TableBill

A map element is not addressable (the map may move its elements when it grows, episode 16), so Go can't take &tables[4].Bill for the pointer method.

Practice

  1. (Homework) Make an Address struct with City and Pin and a Label() method. Embed it in both Customer and Shop (each also has its own Name). Print c.City and s.City through promotion, and each one's label.
  2. (Homework) Write a LoudWriter that embeds io.Writer and uppercases everything written through it. Wrap os.Stdout and print the same receipt as in the video, plain and loud.
  3. Bill has String() returning Rs 25.00 and TableBill embeds Bill. Make fmt.Println(t) print Table 4: Rs 25.00 without changing Bill.
  4. Predict the output of the video's quiz program with Base and Child (below in the quiz), then explain how to make Hello say hi child.
  5. Customer and Waiter both have a Greet() string method, and Order embeds both. Does var g Greeter = Order{...} compile? Fix it so the order greets with the waiter's greeting plus the customer's name.
  6. Using the Seat from the video (*Bill embedded, Add with a pointer receiver), does var a Adder = Seat{&Bill{}, 1} compile, where type Adder interface{ Add(p float64) }? Why?
Solution
  1. Both types get City, Pin and Label by promotion; their own Name is at depth 0, so there's no conflict.
type Address struct {
    City string
    Pin  string
}

func (a Address) Label() string { return a.City + " - " + a.Pin }

type Customer struct {
    Name string
    Address
}

type Shop struct {
    Name string
    Address
}

func main() {
    c := Customer{"Asha", Address{"Pune", "411001"}}
    s := Shop{"Raju Tea Stall", Address{"Mumbai", "400001"}}
    fmt.Println(c.City, s.City)
    fmt.Println(c.Name+":", c.Label())
    fmt.Println(s.Name+":", s.Label())
}
Pune Mumbai
Asha: Pune - 411001
Raju Tea Stall: Mumbai - 400001
  1. LoudWriter's own Write (depth 0) shadows the promoted one, uppercases with bytes.ToUpper, and delegates to the inner writer. It returns len(p): an io.Writer must report how many bytes of p it consumed, not of its own transformed copy (the same for ASCII text, but uppercasing some non-ASCII letters changes their byte length). The value receiver is fine: it changes nothing in the struct.
package main

import (
    "bytes"
    "fmt"
    "io"
    "os"
)

type LoudWriter struct {
    io.Writer
}

func (l LoudWriter) Write(p []byte) (int, error) {
    if _, err := l.Writer.Write(bytes.ToUpper(p)); err != nil {
        return 0, err
    }
    return len(p), nil // report how much of p we consumed
}

func receipt(w io.Writer) {
    fmt.Fprintln(w, "chai    10.00")
    fmt.Fprintln(w, "samosa  15.00")
}

func main() {
    receipt(os.Stdout)
    receipt(LoudWriter{os.Stdout})
}
chai    10.00
samosa  15.00
CHAI    10.00
SAMOSA  15.00
  1. Give TableBill its own String at depth 0. Inside, %v of t.Bill still uses Bill's String. (Don't print t itself inside TableBill.String: that would call String again, forever.) Added to the "fmt.Stringer promotion surprise" program:
func (t TableBill) String() string {
    return fmt.Sprintf("Table %d: %v", t.Table, t.Bill)
}

fmt.Println(t) for TableBill{Bill{25}, 4} then prints:

Table 4: Rs 25.00
  1. Real output: child hi base. To get hi child, Hello must not call b.Name() on the inner value. Make it a function that takes an interface, so the caller's real type decides. With the quiz's Base, Child and both Name methods (and Base.Hello removed):
type Namer interface{ Name() string }

func Hello(n Namer) string { return "hi " + n.Name() }

func main() {
    c := Child{}
    fmt.Println(Hello(c), Hello(c.Base))
}
hi child hi base
  1. No. Both Greet methods are at depth 1, so the selector is ambiguous and Greet is not in Order's method set:
# command-line-arguments
./main.go:19:21: cannot use Order{…} (value of struct type Order) as Greeter value in variable declaration: Order does not implement Greeter (ambiguous selector Order.Greet)

Add a depth-0 method that decides, delegating to the parts:

func (o Order) Greet() string { return o.Waiter.Greet() + ", serving " + o.Customer.Name }
Welcome! I'm Ravi, serving Asha
  1. Yes. Seat embeds *Bill, so the method set of the value Seat includes *Bill's pointer methods (see "Method sets with embedded T vs *T"; the ByPointer example is the same shape and printed 20). If Seat embedded Bill instead, only &Seat{...} would satisfy Adder.

Quick quiz

1. What does this print? (From the video.)

type Base struct{}

func (Base) Name() string { return "base" }
func (b Base) Hello() string { return "hi " + b.Name() }

type Child struct{ Base }

func (Child) Name() string { return "child" }

func main() {
    c := Child{}
    fmt.Println(c.Name(), c.Hello())
}

A. child hi child · B. child hi base · C. base hi base · D. ambiguous selector

Answer

B. c.Name() is Child's own method (depth 0). c.Hello() is promoted from Base and runs on the inner Base value, so b.Name() calls Base's Name: no virtual methods. Real output: child hi base. ((Base) with no receiver name is legal when the method doesn't use the receiver.)

2. type TableBill struct{ B Bill; Table int } and Bill has Total() float64. Does var x Totaler = TableBill{} compile?

Answer

No: TableBill does not implement Totaler (missing method Total). A named field's methods are not promoted. Write struct{ Bill; Table int }.

3. Order embeds Customer and Waiter, both with a Name field. Is the struct declaration itself an error?

Answer

No. Only using o.Name is an error (ambiguous selector o.Name). o.Customer.Name and o.Waiter.Name are fine, and a depth-0 Name field on Order would win over both.

4. Seat embeds *Bill. What happens with var s Seat; fmt.Println(s.No); fmt.Println(s.Sum)?

Answer

It compiles, prints 0, then panics: invalid memory address or nil pointer dereference. s.Sum is s.Bill.Sum, and the embedded pointer is nil.

5. Can you pass a TableBill (which embeds Bill) to func show(b Bill)?

Answer

Not directly: cannot use t (variable of struct type TableBill) as Bill value. Embedding is has-a, not is-a. Pass t.Bill, or make show take an interface that both types satisfy.

Interview questions

1. Does Go have inheritance? How do you reuse code instead?
No: there are no classes, no extends, and no type hierarchy. Go reuses code by composition: a struct contains other types as fields. Embedding (a field with only a type) adds automatic promotion of the inner type's fields and methods, and interfaces provide run-time polymorphism. The Go FAQ describes embedding as analogous, but not identical, to subclassing.

2. What is struct embedding, and what are promoted fields and methods?
An embedded field is declared with only a type (Bill or *Bill); its field name is the type name. Its fields and methods are promoted: t.Items means t.Bill.Items, t.Total() means t.Bill.Total(). Promoted methods join the outer type's method set, so the outer type can satisfy interfaces through them. Promoted fields can't be used as keys in a composite literal.

3. Why is embedding not inheritance? Give two concrete differences.
(a) Is-a vs has-a: a TableBill is not a Bill; var b Bill = t fails with cannot use t ... as Bill value. (b) No virtual methods: a promoted method runs on the inner value, so if Bill.Print calls b.Total(), it calls Bill.Total even when TableBill declares its own Total. In Java, the overriding method would be called. In Go, use an interface parameter for that.

4. Explain the depth rule: shadowing and ambiguous selectors.
Depth is the number of embedded fields between the outer type and a name (own members are depth 0). x.f picks the f at the shallowest depth; deeper ones are shadowed but reachable with the full path. If two fs are at the same shallowest depth, using x.f is a compile error (ambiguous selector), and an ambiguous method is left out of the method set, so interfaces aren't satisfied (ambiguous selector Order.Greet).

5. Embedding T vs *T: what changes?
Ownership and method sets. Embedding T stores a copy inside each outer value; embedding *T shares one T among all holders, but the pointer can be nil and then any promoted field or method access panics. For method sets: with T embedded, the outer value gets only T's value-receiver methods (the outer pointer gets all); with *T embedded, both outer value and pointer get all of T's methods.

6. What is the decorator pattern, and how does embedding an interface help?
A decorator wraps a value with the same interface and adds behaviour (counting, logging, uppercasing) before delegating to it. A struct embedding io.Writer gets Write promoted, overrides it with its own Write that adds behaviour and calls c.Writer.Write(p), and can wrap any writer. If the interface has many methods, only the changed ones need writing, as sort.Reverse does with Less. Danger: a nil embedded interface compiles but panics when called.

7. Should you embed sync.Mutex in a struct?
It works, and c.Lock() reads well, but Lock and Unlock become part of the type's exported API, so outside code can lock it. Many prefer an unexported named field mu sync.Mutex. Either way, never copy the struct after use; go vet reports passes lock by value.

Glossary

Term Meaning Example
Struct / field a type grouping named values / one of those named values (episode 19) type Bill struct{ Items []float64 }
Selector the x.f form that reaches a field or method t.Items, t.Total()
Inheritance a child class declared as a special kind of a parent class, getting its members and usable as it Java class TableBill extends Bill
Subclass / parent (base) class the child type / the type it inherits from, in class-based languages TableBill / Bill in Java
No inheritance in Go Go has no classes, no extends, no type hierarchy var b Bill = t fails
Duplicate code / DRY the same logic copied in several places / "Don't Repeat Yourself" copy-pasted Total
Struct embedding putting a field with only a type into a struct struct{ Bill; Table int }
Embedded field a field declared with a type and no name; its name is the type's name Bill (named Bill), io.Writer (named Writer)
Outer type / embedded type the struct that embeds / the type that is embedded TableBill / Bill
Promoted field an embedded type's field usable directly on the outer value t.Items = t.Bill.Items
Promoted method an embedded type's method callable on the outer value; it joins the method set t.Total() = t.Bill.Total()
Method set the methods a type has for interfaces (episode 20, 21) TableBill has Total
Composite literal the T{...} syntax that builds a value TableBill{Bill: Bill{}, Table: 4}
Addressable has a memory address Go can take (variables yes, map elements no) t.Add(15) takes &t.Bill
Has-a vs is-a composition ("contains a") vs inheritance ("is a kind of") TableBill has a Bill
Override in inheritance, a child method replacing the parent's for child objects Java Total() in TableBill
Virtual method a method call resolved at run time to the real object's version, even from parent code Java methods; Go structs have none
Dynamic dispatch choosing which method to run at run time (episode 21) t.Total() on a Totaler
Depth how many embedded fields lie between the outer type and a name; own members are 0 Items at depth 1 in TableBill
Shadowing a shallower name hiding a deeper one with the same name TableBill.Total hides Bill.Total
Ambiguous selector a name found twice at the same shallowest depth; compile error when used ambiguous selector o.Name
Embedding a pointer type embedding *T: outer values share one T; may be nil struct{ *Bill; No int }
Nil pointer dereference following a nil pointer; a run-time panic s3.Sum with nil *Bill
Panic a run-time crash that stops the program (episode 26) invalid memory address ...
Embedding an interface in a struct a field of interface type with no name; its methods are promoted struct{ io.Writer; N int }
io.Writer the interface Write(p []byte) (n int, err error) (episode 22) os.Stdout, *strings.Builder
Delegation / forwarding passing a call on to another value to do the work c.Writer.Write(p)
Decorator pattern wrapping a value in another with the same interface that adds behaviour CountingWriter, Discount
Decorating behaviour via embedding embedding an interface and overriding some of its methods sort.Reverse, LoudWriter
Composition building bigger types from smaller parts TableOrder{Order, Table}
Composition over inheritance the principle: prefer combining parts to class trees Go's whole design
Class hierarchy a tree of parent and child classes Java Object → ... → TableBill
Fragile base class problem changes inside a base class silently breaking subclasses avoided: Go has no base classes
Wrapper method the forwarding method the compiler generates for a promoted method <autogenerated>:1 in a trace
sync.Mutex a lock: one goroutine at a time between Lock and Unlock (episode 45) struct{ sync.Mutex; n map[string]int }
Goroutine a function running concurrently, started with go (episode 43) go func() { ... }()
API the set of exported names other code can use promoted Lock becomes API
go vet Go's checker for suspicious code passes lock by value
Test fake / stub a simple stand-in for a real dependency in tests (episode 41) struct embedding a big interface
Interface embedding (in interfaces) listing an interface inside another: union of methods (episode 22) interface{ Reader; Writer }

Summary

  • Copy-paste duplicates code that drifts apart; a named field B Bill reuses it but hides its methods (missing method Total, t.B.Total() everywhere).
  • Embedding is a struct field with only a type (Bill, named Bill). Its fields and methods are promoted: t.Items, t.Total(). Promoted methods join the method set, so the outer type satisfies interfaces through them. Promoted fields can't be keys in composite literals.
  • It is not inheritance: a TableBill has a Bill but is not one (cannot use t ... as Bill value), and there are no virtual methods: a promoted method runs on the inner value, so Bill.Print calls Bill.Total (Total: 100). Use an interface to choose behaviour at run time.
  • Depth rule: the shallowest name wins (shadowing; the deeper one stays reachable via the full path); two names at the same depth give ambiguous selector when used, and drop the method from the method set.
  • Embedded pointers (*Bill) share one value among many (65 65 65) but can be nil and panic. Embedding T vs *T changes which pointer methods the outer value has.
  • Embedding an interface (io.Writer) lets a struct wrap any value and override some methods: the decorator pattern (CountingWriter, sort.Reverse, Discount). A nil embedded interface compiles but panics.
  • Composition over inheritance: build types from small parts; embedding reuses, interfaces choose. No class trees, no fragile base classes.

Next episode: Errors the Go way: the error interface, errors.New, fmt.Errorf, returning errors as the last result, if err != nil, sentinel errors like io.EOF, and custom error types.