These are the notes for Go episode 21. In episode 20 Raju's Bill and Khata (his credit book) both learned to report a total with a Total() method. Now he wants one receipt printer that works for both, and Go's type rules say no. Getting around that, you will invent Go's interfaces: one of the best ideas in the language. You will learn concrete types vs interface types, method signatures, what it means for a type to satisfy (implement) an interface, implicit satisfaction and structural typing (and how they differ from Java/C# and from Python's duck typing), polymorphism with a slice of interfaces, how method sets decide who satisfies an interface, interface values as a pair of dynamic type and dynamic value, the nil interface and the famous typed-nil trap, the empty interface interface{} and its alias any, variadic ...any, fmt.Stringer, and the one-line compile-time check var _ Totaler = Bill{}. The expert corner opens the box: itab and data pointer, unsafe.Sizeof, comparing interfaces with ==, interfaces as map keys, copies, dynamic dispatch cost, and a first look at the error interface. 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, and the pc= and +0x... numbers differ between machines and runs.
The problem: one function, one type
Here are episode 20's types, made small. Bill has a Total method with a value receiver; Khata has one with a pointer receiver (episode 20: the receiver is the value a method is called on, written before the method name). printReceipt takes a Bill. We call it with a Bill, then with a *Khata.
package main
import "fmt"
type Bill struct{ Sum float64 }
func (b Bill) Total() float64 { return b.Sum }
type Khata struct{ Owed float64 }
func (k *Khata) Total() float64 { return k.Owed }
func printReceipt(b Bill) {
fmt.Printf("Total: Rs %.2f\n", b.Total())
}
func main() {
printReceipt(Bill{67.5})
printReceipt(&Khata{17.5})
}
# command-line-arguments
./main.go:19:18: cannot use &Khata{…} (value of type *Khata) as Bill value in argument to printReceipt
- A parameter has exactly one type. Here it is a concrete type: a real type that says exactly how its data is stored in memory, like
Bill(a struct with one float64),*Khata(a pointer),intor[]string. You can create values of a concrete type directly. A*Khatais not aBill, even though both have aTotalmethod that returns a float64. Go never converts one struct type into another silently. - Copying the function as
printKhataReceiptworks, but then again for every new type. WhatprintReceiptreally needs isn't aBill. It needs anything that can tell it a total.
Interface types: a job that needs a driving licence
Think of a job ad for a driver. It doesn't name a person. It lists an ability: "must be able to drive".
| Hiring a driver | In Go | Name |
|---|---|---|
| The job ad: "must be able to drive" | interface{ Total() float64 } |
an interface type: a list of abilities |
| Anyone who can drive qualifies; no company badge needed | a type with a Total() float64 method fits |
implicit satisfaction |
| The passenger gets the same ride from any driver | t.Total() runs Bill's or Khata's Total |
polymorphism: one call, many types |
- An interface type is a type that lists method signatures. A method signature is a method's name with its parameter types and result types, without a body:
Total() float64means "a method called Total, taking nothing, returning a float64". - A type satisfies an interface (we also say it implements it) when it has every method in the list, with exactly the same signatures. In Go you never write
implements. A type satisfies an interface just by having the methods. This is called implicit satisfaction.Billwas written beforeTotalerexisted, and it still fits. - Matching by what methods a type has, not by its name or a declaration, is called structural typing ("the structure decides"). Java and C# use nominal typing ("the name decides"):
class Bill implements Totalermust be written, or aBillis not aTotalereven with the right method. - Duck typing ("if it walks like a duck and quacks like a duck, it's a duck") is the same idea in Python and JavaScript, but checked only when the program runs: a missing method crashes at run time. Go's structural typing is checked by the compiler, so you get the flexibility of duck typing with the safety of a compile error.
- Polymorphism (Greek for "many shapes") means one piece of code works with values of many types, each behaving in its own way.
Your first interface
package main
import "fmt"
type Totaler interface{ Total() float64 }
type Bill struct{ Sum float64 }
func (b Bill) Total() float64 { return b.Sum }
type Khata struct{ Owed float64 }
func (k *Khata) Total() float64 { return k.Owed }
func printReceipt(t Totaler) {
fmt.Printf("%T total: Rs %.2f\n", t, t.Total())
}
func main() {
printReceipt(Bill{67.5})
printReceipt(&Khata{17.5})
}
main.Bill total: Rs 67.50
*main.Khata total: Rs 17.50
type Totaler interface{ Total() float64 }declares an interface type namedTotalerwith one method. Longer interfaces list one method per line inside the braces.- Naming convention: a one-method interface is named after its method plus -er:
Total→Totaler,String→Stringer,Read→Reader,Write→Writer.BillandKhatasay nothing aboutTotaler; they simply have the method. %Tshows the real type inside the interface:main.Bill, then*main.Khata. The sameprintReceiptcalled two differentTotalmethods. You just invented interfaces.
Polymorphism: the whole day in one slice
A new type, Tip, is a float64 with its own Total. A slice of Totaler can hold a Bill, a *Khata and a Tip together.
package main
import "fmt"
type Totaler interface{ Total() float64 }
type Bill struct{ Sum float64 }
func (b Bill) Total() float64 { return b.Sum }
type Khata struct{ Owed float64 }
func (k *Khata) Total() float64 { return k.Owed }
type Tip float64
func (t Tip) Total() float64 { return float64(t) }
func main() {
day := []Totaler{Bill{67.5}, &Khata{17.5}, Tip(10)}
var sum float64
for _, t := range day {
sum += t.Total()
}
fmt.Println(len(day), "things, Rs", sum)
}
3 things, Rs 95
[]Totaleris a slice whose elements have an interface type. Each element can hold a different concrete type.- The loop doesn't know or care which is which.
t.Total()runs the right method for each one. Tomorrow Raju adds aDeliverytype with aTotalmethod, and this loop works without a single change. That's the real win: code that uses an interface is open to new types you haven't written yet. - Any named type can have methods, including one based on float64 (
Tip), so any of them can satisfy an interface.
Who satisfies an interface? Method sets decide
What doesn't fit? A Coupon with no Total method, and a Khata value, not a pointer.
package main
import "fmt"
type Totaler interface{ Total() float64 }
type Coupon struct{ Code string }
type Khata struct{ Owed float64 }
func (k *Khata) Total() float64 { return k.Owed }
func main() {
var t Totaler
t = Coupon{"CHAI10"}
t = Khata{17.5}
fmt.Println(t)
}
# command-line-arguments
./main.go:15:9: cannot use Coupon{…} (value of struct type Coupon) as Totaler value in assignment: Coupon does not implement Totaler (missing method Total)
./main.go:16:9: cannot use Khata{…} (value of struct type Khata) as Totaler value in assignment: Khata does not implement Totaler (method Total has pointer receiver)
- The compiler reports both mistakes at once, with the reason for each.
(missing method Total):Couponhas noTotalat all. (method Total has pointer receiver): subtler. Recall method sets from episode 20. The method set of a type is the list of methods you can call on a value of that type through an interface:- the method set of
T(a value) contains only methods with value receivers(t T); - the method set of
*T(a pointer) contains methods with value receivers and pointer receivers(t *T). Khata'sTotalhas a pointer receiver, so it is in the method set of*Khata, not ofKhata. Only&Khata{...}satisfiesTotaler.Bill'sTotalhas a value receiver, so bothBill{}and&Bill{}satisfy it.- When you call
k.Total()on an addressable variablek, Go takes&kfor you. With interfaces it won't, because an interface stores its own copy of the value, and a pointer method would change the copy, not your variable (more in "Copies and comparisons" below).
| Type | Method (b Bill) Total() |
Method (k *Khata) Total() |
|---|---|---|
value Bill / Khata satisfies Totaler? |
yes | no (pointer receiver) |
pointer *Bill / *Khata satisfies Totaler? |
yes | yes |
Interface values: a delivery box with a label
What is actually stored in a variable of interface type? Think of a delivery box.
| A parcel | An interface value | Name |
|---|---|---|
| The label: "contains: a Bill" | %T → main.Bill |
the dynamic type |
| The thing inside | %v → {67.5} |
the dynamic value |
| No label, empty box | both parts nil, t == nil |
the nil interface |
- An interface value is what an interface-typed variable holds: always a pair of (type, value).
- The dynamic type is the concrete type of the value stored right now. "Dynamic" means it can change while the program runs. The type written in the declaration,
Totaler, is the static type: it never changes. The dynamic value is the concrete value itself: the bill inside the box. - A nil interface has no label and nothing inside: dynamic type nil and dynamic value nil. It is the zero value of every interface type.
package main
import "fmt"
type Totaler interface{ Total() float64 }
type Bill struct{ Sum float64 }
func (b Bill) Total() float64 { return b.Sum }
type Khata struct{ Owed float64 }
func (k *Khata) Total() float64 { return k.Owed }
func main() {
var t Totaler
fmt.Printf("%v %T %v\n", t, t, t == nil)
t = Bill{67.5}
fmt.Printf("%v %T\n", t, t)
t = &Khata{17.5}
fmt.Printf("%v %T\n", t, t)
t = nil
fmt.Println(t.Total())
}
<nil> <nil> true
{67.5} main.Bill
&{17.5} *main.Khata
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x49363e]
goroutine 1 [running]:
main.main()
/tmp/.../main.go:24 +0x17e
exit status 2
<nil> <nil> true: no type, no value, sot == nil.- The same variable then held a
main.Bill, then a*main.Khata: its dynamic type changed while the program ran.%vof a pointer to a struct prints&{17.5}.t = nilempties the box again. - Calling a method on a nil interface panics:
invalid memory address or nil pointer dereference. There is no type inside, so Go has noTotalto call. A panic is a run-time crash that stops the program (episode 25);SIGSEGVis the operating system's signal for touching memory at address 0.
The nil interface trap
Now the trap that catches even experienced developers. find looks up a khata by name. It starts with k, a nil *Khata, fills it only for Asha, and returns k as a Totaler. The caller checks t != nil before using it. Looks safe. Find Ravi:
package main
import "fmt"
type Totaler interface{ Total() float64 }
type Khata struct{ Owed float64 }
func (k *Khata) Total() float64 { return k.Owed }
func find(name string) Totaler {
var k *Khata // nil: no khata yet
if name == "Asha" {
k = &Khata{17.5}
}
return k
}
func main() {
t := find("Ravi")
fmt.Printf("%T %v %v\n", t, t, t == nil)
if t != nil {
fmt.Println(t.Total())
}
}
*main.Khata <nil> false
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x49354a]
goroutine 1 [running]:
main.(*Khata).Total(...)
/tmp/.../main.go:9
main.main()
/tmp/.../main.go:23 +0xca
exit status 2
*main.Khata <nil> false:tis not nil! The box has a label,*Khata, even though the thing inside is a nil pointer.- So the
if t != nilcheck passes,Totalruns withk == nil, andk.Oweddereferences a nil pointer. The trace shows the panic insidemain.(*Khata).Total. - An interface is nil only when both its type and its value are nil. An interface holding a nil pointer is often called a typed nil: the value is nil, but it has a type.
Two kinds of "nil"
| Box | Dynamic type | Dynamic value | t == nil |
|---|---|---|---|
| nil interface | nil | nil | true |
interface holding a nil *Khata |
*Khata |
nil pointer | false |
- ✗
var k *Khata; return kas aTotaler→ the caller sees a non-nil interface. - ✓ When there is nothing to return,
return nildirectly. - ★ The same trap appears with
error, which is an interface too: never return a nil*MyErroras anerror. Episode 24 comes back to it.
The fix
package main
import "fmt"
type Totaler interface{ Total() float64 }
type Khata struct{ Owed float64 }
func (k *Khata) Total() float64 { return k.Owed }
func find(name string) Totaler {
if name == "Asha" {
return &Khata{17.5}
}
return nil // a truly nil interface
}
func main() {
t := find("Ravi")
fmt.Printf("%T %v %v\n", t, t, t == nil)
if t != nil {
fmt.Println(t.Total())
}
}
<nil> <nil> true
The check works, and nothing panics.
Expert note: a pointer method can be safe on a nil receiver if it checks itself: with if k == nil { return 0 } at the top of Total, var k *Khata; var t Totaler = k; fmt.Println(t != nil, t.Total()) really prints true 0. That's legal and sometimes useful, but the interface is still not nil.
The empty interface and any: a job ad with no requirements
| Hiring | In Go | Name |
|---|---|---|
| "Anyone can apply": no skills listed | interface{}: zero methods |
the empty interface |
| A short name on the same ad | type any = interface{} |
any, an alias |
| "But what can they do?" You don't know yet | x + 1 fails |
you must ask first (episode 22) |
- An interface with zero methods is the empty interface, written
interface{}. Every type has at least zero methods, so every type satisfies it: ints, strings, structs, slices, pointers, functions, even other interfaces. - Since Go 1.18 it has a short name,
any.anyis a type alias (episode 19):type any = interface{}. Exactly the same type, just shorter. - The catch: if anyone can apply, you know nothing about what they can do. You can store anything in an
any, but you can't do much with it.
package main
import "fmt"
func describe(x any) {
fmt.Printf("%-6v %T\n", x, x)
}
func main() {
things := []any{"chai", 3, 12.5, true, nil}
for _, x := range things {
describe(x)
}
var e interface{} = "same as any"
fmt.Println(e)
}
chai string
3 int
12.5 float64
true bool
<nil> <nil>
same as any
- Each value keeps its dynamic type:
string,int,float64,bool. The untyped constants3and12.5got their default typesintandfloat64(episode 5) when they were put in the box. nilin a[]anyis a nil interface:%Tprints<nil>.
Variadic ...any: how fmt.Println accepts anything
fmt.Println's real signature is func Println(a ...any) (n int, err error). ...any is a variadic parameter (episode 9): any number of arguments, collected into a []any. You can write your own:
package main
import "fmt"
func logAll(vals ...any) {
fmt.Println(vals...)
fmt.Printf("%d values, type %T\n", len(vals), vals)
}
func main() {
logAll("chai", 3, 12.5, true)
}
chai 3 12.5 true
4 values, type []interface {}
- Inside the function,
valsis a[]any;%Tprints its full spelling[]interface {}(the same type).fmt.Println(vals...)spreads the slice back into separate arguments.
You can't do arithmetic on an any
package main
import "fmt"
// any can hold anything
func main() {
var x any = 3
fmt.Println(x + 1)
}
# command-line-arguments
./main.go:9:17: invalid operation: x + 1 (mismatched types any and int)
- The compiler only knows
xis anany, andanyhas no+. It doesn't matter that anintis inside right now. To get theintback out you need a type assertion,x.(int): next episode. - Use
anyonly when you truly accept everything (printing, JSON, generic containers). A small interface with real methods tells the compiler, and the reader, much more.
fmt.Stringer: the interface you already used
In episode 20, fmt printed Rupees using its String method. That works because the fmt package declares type Stringer interface{ String() string }: fmt.Stringer is an interface with one method, String, returning a string. When Println, Printf("%v") or %s gets a value whose dynamic type satisfies fmt.Stringer, it calls String() instead of the default format.
package main
import "fmt"
type Rupees float64
func (r Rupees) String() string {
return fmt.Sprintf("Rs %.2f", float64(r))
}
type Table struct{ No int }
func (t *Table) String() string {
return fmt.Sprintf("Table #%d", t.No)
}
func main() {
var s fmt.Stringer = Rupees(67.5)
fmt.Println(s)
t := Table{4}
fmt.Println(t, &t)
}
Rs 67.50
{4} Table #4
Rs 67.50came through the interface:Rupeessatisfiesfmt.Stringer.t(a value) printed as the plain default{4}, while&tprintedTable #4.Table'sStringhas a pointer receiver, so it is only in*Table's method set. ATablevalue doesn't satisfyfmt.Stringer, andfmtquietly falls back to the default format. No error, no warning.- Rule of thumb: give
String()a value receiver unless it truly needs a pointer, or always print&t. Never callfmt.Sprint(r)or%von the receiver itself insideString(): it callsString()again, forever. Convert first, as withfloat64(r).
Many standard types are Stringers
With import ("fmt"; "net"; "time"):
func main() {
things := []fmt.Stringer{2*time.Hour + 30*time.Minute, time.Saturday, net.IPv4(192, 168, 1, 10)}
for _, s := range things {
fmt.Printf("%-14T %s\n", s, s.String())
}
}
time.Duration 2h30m0s
time.Weekday Saturday
net.IP 192.168.1.10
None of these packages know about your slice. They just have a String() string method.
Compile-time checks: var _ Totaler = Bill{}
Last danger: someone renames Bill's Total to Amount. If nothing in this file uses a Bill as a Totaler yet, nothing complains until some other code breaks, maybe in another package, maybe weeks later. The fix is one line:
package main
import "fmt"
type Totaler interface{ Total() float64 }
type Bill struct{ Sum float64 }
func (b Bill) Amount() float64 { return b.Sum } // renamed!
var _ Totaler = Bill{} // compile-time check
func main() {
fmt.Println(Bill{67.5})
}
# command-line-arguments
./main.go:11:17: cannot use Bill{} (value of struct type Bill) as Totaler value in variable declaration: Bill does not implement Totaler (missing method Total)
var _ Totaler = Bill{}declares a package-level variable of typeTotalerand assigns aBillto it, so the compiler must check thatBillsatisfiesTotaler.- Its name is
_, the blank identifier (episode 3): a write-only name that throws the value away. It costs nothing at run time, and never triggers "declared and not used". The error points right at the check line, with the reason. - For pointer-receiver methods, check the pointer type:
var _ Totaler = (*Khata)(nil).(*Khata)(nil)convertsnilto the type*Khata: a typed nil pointer that allocates nothing.
With Bill (value receiver) and Khata (pointer receiver) from the start of these notes, this block compiles, and the program runs:
var (
_ Totaler = Bill{}
_ Totaler = (*Bill)(nil)
_ Totaler = (*Khata)(nil)
)
Checking the value Khata{} instead fails with the familiar reason (real run, line 12 was var _ Totaler = Khata{}):
./main.go:12:17: cannot use Khata{} (value of struct type Khata) as Totaler value in variable declaration: Khata does not implement Totaler (method Total has pointer receiver)
These checks are common in the standard library and large codebases, placed right next to the type.
Expert corner: inside the box
Two words: itab and data pointer
An interface value is stored as two machine words (8 bytes each on a 64-bit machine):
- a type word: for a non-empty interface like
Totaler, a pointer to an itab ("interface table"), a small table the runtime builds once per (interface type, concrete type) pair. It records the concrete type and the addresses of the methods the interface needs (here,Bill.Total). The empty interfaceanyhas no methods to look up, so its type word points straight at the concrete type descriptor. The Go runtime calls the two layouts iface (non-empty interface) and eface (empty interface). - a data word: a pointer to the dynamic value. A pointer value (like
*Khata) is stored directly; other values are usually copied somewhere (often the heap) and the word points at the copy.
A nil interface has both words zero. An interface holding a nil *Khata has a non-zero type word and a zero data word: exactly why it is not == nil.
package main
import (
"fmt"
"unsafe"
)
type Totaler interface{ Total() float64 }
type Bill struct{ Sum float64 }
func (b Bill) Total() float64 { return b.Sum }
func main() {
var t Totaler = Bill{67.5}
var a any = 3
var p *Bill
big := [100]float64{}
var t2 any = big
fmt.Println(unsafe.Sizeof(t), unsafe.Sizeof(a), unsafe.Sizeof(p))
fmt.Println(unsafe.Sizeof(big), unsafe.Sizeof(t2))
}
16 16 8
800 16
unsafe.Sizeof(episode 19) gives a value's size in bytes. Every interface value is 16 bytes on amd64, two 8-byte words, whatever is inside. A pointer is 8.- An 800-byte array in an
anystill makes a 16-byte interface: the array lives elsewhere and the data word points at it.
Calling a method: dynamic dispatch
t.Total() on an interface means: read the itab from the type word, find Total's address in it, call it with the data word as the receiver. Choosing the function at run time like this is dynamic dispatch; a direct call b.Total() is static dispatch (the compiler knows the function, and can usually inline it: paste its body at the call site). A real run of testing.Benchmark summing 1000 Bills, once through []Bill and once through []Totaler:
the direct loop sink += bills[i].Total() took 2.53 ns per call and the interface loop sink += t.Total() 2.68 ns (one run; numbers vary by machine and run). A fraction of a nanosecond: modern CPUs predict indirect calls well. Use interfaces freely for clarity, and measure (benchmarks, episode 40) before optimizing them away in a hot loop.
Copies and comparisons
Putting a value in an interface copies it, like any assignment, unless the value is a pointer. And two interface values are == when they have the same dynamic type and equal dynamic values (or both are nil).
package main
import "fmt"
type Totaler interface{ Total() float64 }
type Bill struct{ Sum float64 }
type Khata struct{ Owed float64 }
type Tip float64
func (b Bill) Total() float64 { return b.Sum }
func (k *Khata) Total() float64 { return k.Owed }
func (t Tip) Total() float64 { return float64(t) }
func main() {
b, k := Bill{67.5}, &Khata{17.5}
var t, u Totaler = b, k
b.Sum, k.Owed = 100, 50
fmt.Println(t.Total(), u.Total()) // copy vs shared pointer
var x, y Totaler = Bill{10}, Bill{10}
var z Totaler = Tip(10)
fmt.Println(x == y, x == z, x.Total() == z.Total())
var m, n any = 3, 3.0
fmt.Println(m == n, m == 3)
var s1, s2 any = []int{1}, []int{1}
fmt.Println(s1 == s2)
}
67.5 50
true false true
false true
panic: runtime error: comparing uncomparable type []int
goroutine 1 [running]:
main.main()
/tmp/.../main.go:28 +0x265
exit status 2
tkept its own copy of the bill (67.5), whileuholds a copy of the pointer and sees50. This is why aKhatavalue can't satisfyTotalerwhenTotalneeds a pointer: the box's copy isn't addressable, so there's no safe pointer to give the method.x == zis false: aBilland aTipare different types, even though both totals are 10.m == nis false too (int3 vsfloat643), whilem == 3is true: the constant becomes anintin an interface, and both parts match.- Comparing interfaces whose dynamic type is not comparable (slices, maps, functions; episode 19) compiles but panics at run time: the compiler can't know what's inside.
- So interfaces can be map keys (practice 5), with the same danger: a
[]intkey in amap[any]stringpanics withruntime error: hash of unhashable type []int.
Interfaces with several methods
An interface can list any number of methods; a type must have all of them.
package main
import "fmt"
type Item interface {
Name() string
Price() float64
}
type Chai struct{ Cups int }
type Samosa struct{ Plates int }
func (c Chai) Name() string { return "chai" }
func (c Chai) Price() float64 { return 12.5 * float64(c.Cups) }
func (s Samosa) Name() string { return "samosa" }
func (s Samosa) Price() float64 { return 30 * float64(s.Plates) }
func main() {
order := []Item{Chai{3}, Samosa{1}}
for _, it := range order {
fmt.Printf("%-7s %6.2f\n", it.Name(), it.Price())
}
}
chai 37.50
samosa 30.00
A type Water struct{} with only a Name method fails var it Item = Water{} with Water does not implement Item (missing method Price). Go style prefers small interfaces of one or two methods ("the bigger the interface, the weaker the abstraction", Rob Pike). Episode 22 covers interface design and embedding interfaces (io.ReadWriter).
A preview: error is an interface
The err you've seen from fmt.Scan has a built-in interface type: type error interface{ Error() string }. Any type with an Error() string method is an error:
package main
import (
"errors"
"fmt"
"strconv"
)
type OutOfMilk struct{ Litres int }
func (e OutOfMilk) Error() string { return fmt.Sprintf("out of milk: %d litres left", e.Litres) }
func main() {
var err error = OutOfMilk{0}
fmt.Println(err)
_, err = strconv.Atoi("three")
fmt.Printf("%T: %v\n", err, err)
err = errors.New("stall closed")
fmt.Printf("%T: %v\n", err, err)
}
out of milk: 0 litres left
*strconv.NumError: strconv.Atoi: parsing "three": invalid syntax
*errors.errorString: stall closed
err != nil is just today's nil-interface check, and the typed-nil trap applies to errors too. Episode 24 is all about errors.
Mini project: a receipt printer for any Totaler
Bill and Tip each have Total and String, so each satisfies both Totaler and fmt.Stringer. printReceipt is variadic: it takes any number of Totalers.
package main
import "fmt"
type Totaler interface{ Total() float64 }
type Bill struct{ Sum float64 }
type Tip float64
func (b Bill) Total() float64 { return b.Sum }
func (b Bill) String() string { return "Bill" }
func (t Tip) Total() float64 { return float64(t) }
func (t Tip) String() string { return "Tip" }
func printReceipt(items ...Totaler) {
var sum float64
for _, t := range items {
fmt.Printf("%-6v %6.2f\n", t, t.Total())
sum += t.Total()
}
fmt.Printf("%-6s %6.2f\n", "Total", sum)
}
func main() {
printReceipt(Bill{67.5}, Tip(10), Bill{30})
}
Bill 67.50
Tip 10.00
Bill 30.00
Total 107.50
%-6vprints each item through itsStringmethod, left-aligned in 6 characters (episode 18). The sametis used as aTotaler(forTotal) and, insidePrintf, as ananythat fmt finds is aStringer.printReceiptnever namesBillorTip.
Extended version: a named Khata, table numbers and compile-time checks
Asha's khata needs her name on the receipt, and bills show their table. *Khata gets a String method too, and compile-time checks guard every type.
package main
import "fmt"
type Totaler interface{ Total() float64 }
type Bill struct {
Table int
Sum float64
}
type Tip float64
type Khata struct {
Name string
Owed float64
}
func (b Bill) Total() float64 { return b.Sum }
func (b Bill) String() string { return fmt.Sprintf("Table %d", b.Table) }
func (t Tip) Total() float64 { return float64(t) }
func (t Tip) String() string { return "Tip" }
func (k *Khata) Total() float64 { return k.Owed }
func (k *Khata) String() string { return "Khata: " + k.Name }
// compile-time checks: each type must be a Totaler and a fmt.Stringer
var (
_ Totaler = Bill{}
_ Totaler = Tip(0)
_ Totaler = (*Khata)(nil)
_ fmt.Stringer = (*Khata)(nil)
)
func printReceipt(items ...Totaler) {
var sum float64
for i, t := range items {
fmt.Printf("%2d. %-12v %8.2f\n", i+1, t, t.Total())
sum += t.Total()
}
fmt.Println(" -----------------------")
fmt.Printf(" %-12s %8.2f\n", "Total", sum)
}
func main() {
asha := &Khata{Name: "Asha", Owed: 17.5}
day := []Totaler{Bill{4, 67.5}, Tip(10), asha, Bill{7, 30}}
asha.Owed += 12.5 // Asha takes two more chai on credit
printReceipt(day...)
}
1. Table 4 67.50
2. Tip 10.00
3. Khata: Asha 30.00
4. Table 7 30.00
-----------------------
Total 137.50
printReceipt(day...)spreads a[]Totalerinto the variadic parameter.ashais a pointer, so the receipt shows Asha's updated30.00, changed after she was put in the slice. Try it: passKhata{Name: "Ravi", Owed: 5}(no&) and read the error; then add aDeliverytype with a fee and watchprintReceiptwork unchanged.
The next problem: Raju wants to print Asha's phone number only on khata lines. Inside printReceipt, t is just a Totaler, and a Totaler has no fields at all (t.Owed undefined, below). How do you ask the box what's really inside, and take it out? Next episode: type assertions and type switches.
Common mistakes (and the real messages)
| You wrote | Real error / what happens | Fix |
|---|---|---|
printReceipt(b Bill) called with &Khata{17.5} |
cannot use &Khata{…} (value of type *Khata) as Bill value in argument to printReceipt |
take an interface: t Totaler |
t = Coupon{"CHAI10"} (no Total) |
Coupon does not implement Totaler (missing method Total) |
add the method |
var t Totaler = Khata{17.5} |
Khata does not implement Totaler (method Total has pointer receiver) |
&Khata{17.5} |
func (b Bill) Total() int |
Bill does not implement Totaler (wrong type for method Total) then have Total() int / want Total() float64 |
match the signature exactly |
t.Owed on a Totaler |
t.Owed undefined (type Totaler has no field or method Owed) |
only interface methods are visible; type assertion (episode 22) |
var k *Khata; return k as a Totaler |
caller's t != nil is true, then invalid memory address or nil pointer dereference |
return nil |
var x any = 3; x + 1 |
invalid operation: x + 1 (mismatched types any and int) |
type assertion x.(int) (episode 22) |
sum(bills) with bills []Bill, func sum(ts []Totaler) |
cannot use bills (variable of type []Bill) as []Totaler value in argument to sum |
build a []Totaler with a loop |
func show(t *Totaler) then t.Total() |
t.Total undefined (type *Totaler is pointer to interface, not interface) |
take t Totaler; an interface can already hold a pointer |
String() with a pointer receiver, fmt.Println(t) |
no error: prints the default {4} |
value receiver, or print &t |
== on interfaces holding slices |
panic: runtime error: comparing uncomparable type []int |
compare only comparable dynamic types |
| a method renamed, nothing uses the type as an interface yet | no error until other code breaks | var _ Totaler = Bill{} |
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 wrong-signature error, in full (Bill{ Sum int } with func (b Bill) Total() int, line 12 var t Totaler = Bill{67}):
# command-line-arguments
./main.go:12:21: cannot use Bill{…} (value of struct type Bill) as Totaler value in variable declaration: Bill does not implement Totaler (wrong type for method Total)
have Total() int
want Total() float64
A []Bill is not a []Totaler: each Totaler element is a 16-byte (type, value) pair while each Bill is 8 bytes, so the layouts differ and Go won't convert the whole slice. Box each bill in a loop: ts := make([]Totaler, len(bills)), then for i, b := range bills { ts[i] = b }, and sum(ts) (real output 30 for []Bill{{10}, {20}}).
And a pointer to an interface is almost always a mistake: an interface value is already small and can hold a pointer itself.
Practice
- (Homework) Write a
Shapeinterface withArea() float64.Squaregets a value-receiverAreaand aString()method;Circlegets a pointer-receiverArea. Addvar _ ...checks, sum the areas ofSquare{2},&Circle{1},Square{3}, and print the slice. Explain the odd last line. - In practice 1, what does
var _ Shape = Circle{}say? khatasis amap[string]*Khata. WritefindBad, which returnskhatas[name]directly as aTotaler, andfindGood, which avoids the nil trap. Print== nilfor an unknown name.- With
Totaler,BillandKhataas in "Copies and comparisons", predict:b := Bill{10}; k := &Khata{10}; var t1, t2 Totaler = b, k; b.Sum, k.Owed = 99, 99; fmt.Println(t1.Total(), t2.Total()). - Count how many times each Totaler appears in
[]Totaler{Bill{10}, Tip(10), Bill{10}}with amap[Totaler]int. Also printa == Bill{10}anda == Tip(10)forvar a Totaler = Bill{10}. - What do
var x any = 'c'; fmt.Printf("%v %T\n", x, x)anditems := []any{"chai", 3}; fmt.Println(items...)print?
Solution
- 4 + π + 9 ≈ 16.14.
Printlnof the slice usesSquare'sString, but prints the*Circleelement as a hex address: inside a slice, fmt prints pointers that way instead of&{...}(the number varies between runs). At the top level,%vprints&{1}. Give*CircleaString()too to fix it.
package main
import (
"fmt"
"math"
)
type Shape interface{ Area() float64 }
type Square struct{ Side float64 }
type Circle struct{ R float64 }
func (s Square) Area() float64 { return s.Side * s.Side }
func (s Square) String() string { return fmt.Sprintf("Square(%g)", s.Side) }
func (c *Circle) Area() float64 { return math.Pi * c.R * c.R }
var (
_ Shape = Square{}
_ fmt.Stringer = Square{}
_ Shape = (*Circle)(nil)
)
func main() {
shapes := []Shape{Square{2}, &Circle{1}, Square{3}}
var sum float64
for _, s := range shapes {
fmt.Printf("%v -> %.2f\n", s, s.Area())
sum += s.Area()
}
fmt.Printf("total %.2f\n", sum)
fmt.Println(shapes)
}
Square(2) -> 4.00
&{1} -> 3.14
Square(3) -> 9.00
total 16.14
[Square(2) 0xc00008a040 Square(3)]
- A real run with that line (line 10 of the file):
./main.go:10:15: cannot use Circle{} (value of struct type Circle) as Shape value in variable declaration: Circle does not implement Shape (method Area has pointer receiver)
- A missing map key gives the zero value of
*Khata, a nil pointer, sofindBadreturns a typed nil.
With Totaler and Khata as in the nil trap:
var khatas = map[string]*Khata{"Asha": {17.5}}
func findBad(name string) Totaler { return khatas[name] } // typed nil for "Ravi"
func findGood(name string) Totaler {
k, ok := khatas[name]
if !ok {
return nil
}
return k
}
func main() {
fmt.Println(findBad("Ravi") == nil, findGood("Ravi") == nil)
if t := findGood("Asha"); t != nil {
fmt.Println(t.Total())
}
}
false true
17.5
-
Real output
10 99:t1holds its own copy of the bill,t2a copy of the pointer, so onlyt2sees the change. -
Comparing an interface with a concrete value converts the value to the interface first, then compares (type, value).
Bill{10}andTip(10)are different keys.
With Totaler, Bill and Tip declared as in "Copies and comparisons":
func main() {
var a Totaler = Bill{10}
fmt.Println(a == Bill{10}, a == Tip(10), a == Totaler(Bill{10}))
counts := map[Totaler]int{}
for _, t := range []Totaler{Bill{10}, Tip(10), Bill{10}} {
counts[t]++
}
fmt.Println(counts[Bill{10}], counts[Tip(10)], len(counts))
}
true false true
2 1 2
- Real output
99 int32andchai 3: a rune literal is anint32(episode 17), so the box holds the number 99. Spreading a[]anywithitems...passes its elements one by one; passingitemswithout...would make it one argument, printing[chai 3].
Quick quiz
1. What does this print? (From the video.)
type Shape interface{ Area() float64 }
type Sq struct{ s float64 }
func (q *Sq) Area() float64 { return q.s * q.s }
func main() {
var p *Sq
var s Shape = p
fmt.Println(p == nil, s == nil)
}
A. true true · B. true false · C. false false · D. compile error
Answer
B. p is a nil *Sq, so p == nil is true. s holds the type *Sq with a nil value inside, so the interface is not nil. Real output: true false.
2. With func (k *Khata) Total() float64, does var t Totaler = Khata{17.5} compile?
Answer
No: Khata does not implement Totaler (method Total has pointer receiver). Total is only in the method set of *Khata; write &Khata{17.5}.
3. Table has func (t *Table) String() string { return fmt.Sprintf("Table #%d", t.No) }. What does t := Table{4}; fmt.Println(t, &t) print?
Answer
{4} Table #4. The value Table doesn't satisfy fmt.Stringer (pointer receiver), so fmt silently uses the default format for t.
4. Does var x any = 3; fmt.Println(x + 1) print 4?
Answer
No, it doesn't compile: invalid operation: x + 1 (mismatched types any and int). The compiler only knows x is an any; you need a type assertion x.(int) (episode 22).
5. var a Totaler = Bill{10} and var c Totaler = Tip(10). What is a == c? And a.Total() == c.Total()?
Answer
false and true. Interface equality needs the same dynamic type and equal values; Bill and Tip are different types. The totals are both the float64 10. Real output: true false true for a == b, a == c, a.Total() == c.Total().
Interview questions
1. What is an interface in Go, and how does a type implement one?
An interface type is a set of method signatures. A type implements (satisfies) it by having all those methods with identical signatures; there is no implements keyword. This is implicit satisfaction. It lets you write interfaces for types you didn't write (even from other packages), and lets the standard library's fmt.Stringer, io.Writer and error work with your types automatically.
2. Structural vs nominal typing: how does Go compare with Java and with Python?
Java and C# are nominal: a class must declare implements Totaler. Go is structural: having the methods is enough. Python's duck typing has the same "has the methods" idea but checks at run time; Go checks at compile time, so a missing method is a compile error (does not implement Totaler (missing method Total)), not a crash.
3. Why doesn't a value T satisfy an interface when the method has a pointer receiver?
Method sets: T's method set has only value-receiver methods; *T's has both. An interface stores a copy of the value, and that copy isn't addressable, so Go can't safely take its address to call a pointer method (any changes would be lost). So only *T satisfies it: (method Total has pointer receiver).
4. What is inside an interface value? When is it nil?
Two words: a type word (a pointer to an itab for non-empty interfaces, or directly to the type descriptor for any) and a data word pointing at (or holding) the dynamic value. unsafe.Sizeof gives 16 bytes on amd64. It is nil only when both are nil. Storing a nil pointer sets the type word, so the interface is non-nil: the typed-nil trap, common with error returns. Fix: return a literal nil.
5. What is any? When should you use it?
any is an alias for interface{}, the empty interface, added in Go 1.18. Every type satisfies it, so it can hold any value (fmt.Println(a ...any), JSON decoding, containers). But it has no methods or operators, so you lose compile-time checking and need type assertions to use the value. Prefer a small interface with real methods, or generics (episode 23), when you know what you need.
6. Can you compare interface values? Use them as map keys?
Yes: == is true when the dynamic types are identical and the dynamic values are equal, or both are nil. If the dynamic type is not comparable (slice, map, func), the comparison compiles but panics at run time: runtime error: comparing uncomparable type []int; as a map key, hash of unhashable type []int.
7. What does var _ io.Writer = (*MyWriter)(nil) do?
It's a compile-time assertion that *MyWriter satisfies io.Writer. The blank identifier discards the variable, and (*MyWriter)(nil) is a typed nil pointer, so nothing is allocated and there's no run-time cost. If a method is renamed or its signature changes, the build fails right at that line instead of somewhere far away.
Glossary
| Term | Meaning | Example |
|---|---|---|
| Concrete type | a real type that says exactly how data is stored; you can make values of it | Bill, *Khata, int |
| Interface type | a type that lists method signatures | type Totaler interface{ Total() float64 } |
| Method signature | a method's name, parameter types and result types, without a body | Total() float64 |
| Receiver (value / pointer) | the value a method is called on, written before its name: a copy (t T) or a pointer (t *T) (episode 20) |
(b Bill), (k *Khata) |
| Satisfy / implement | to have every method an interface lists | Bill satisfies Totaler |
| Implicit satisfaction | satisfying an interface with no implements keyword |
Bill never mentions Totaler |
| Structural typing | type compatibility decided by the methods a type has | Go interfaces |
| Nominal typing | compatibility decided by declared names | Java class Bill implements Totaler |
| Duck typing | "has the methods" checked only at run time | Python, JavaScript |
| Polymorphism | one piece of code working with many types | t.Total() in a loop over []Totaler |
-er naming |
one-method interfaces are named after the method + er | Stringer, Reader, Totaler |
| Method set | the methods callable on a type through an interface | *Khata has Total; Khata doesn't |
| Interface value | the (dynamic type, dynamic value) pair an interface variable holds | t = Bill{67.5} |
| Static type | the declared type of a variable; never changes | Totaler |
| Dynamic type | the concrete type stored in an interface right now | %T → main.Bill |
| Dynamic value | the concrete value stored in an interface | {67.5} |
| Nil interface | an interface with no type and no value; the zero value | var t Totaler → t == nil |
| Typed nil | an interface holding a nil pointer; not == nil |
*main.Khata <nil> false |
| Panic | a run-time crash that stops the program (episode 25) | nil pointer dereference |
| Empty interface | interface{}: no methods, satisfied by every type |
var e interface{} = "x" |
any |
alias for interface{} since Go 1.18 |
func describe(x any) |
| Type alias | a second name for the same type (episode 19) | type any = interface{} |
| Default type | the type an untyped constant gets when stored | 3 → int, 12.5 → float64 |
| Variadic parameter | a last parameter taking any number of arguments as a slice | vals ...any, items ...Totaler |
Spread s... |
passes a slice's elements as separate variadic arguments | printReceipt(day...) |
fmt.Stringer |
interface{ String() string }; fmt uses it to print |
Rupees → Rs 67.50 |
Blank identifier _ |
a name that throws the value away (episode 3) | var _ Totaler = Bill{} |
| Compile-time interface check | a blank variable assignment that makes the compiler verify satisfaction | var _ Totaler = (*Khata)(nil) |
(*T)(nil) |
nil converted to the pointer type *T; allocates nothing |
(*Khata)(nil) |
| itab | the runtime table for one (interface, concrete type) pair: type and method addresses | behind Totaler(Bill{}) |
| iface / eface | the runtime's layout for non-empty / empty interfaces | Totaler / any |
| Data word | the interface word pointing at (or holding) the dynamic value | the "thing inside the box" |
unsafe.Sizeof |
a value's size in bytes | interface = 16 on amd64 |
| Dynamic / static dispatch | choosing the method at run time through the itab / a call the compiler already knows | t.Total() / b.Total() |
| Inlining | the compiler pasting a function's body at the call site | direct calls of tiny methods |
| Comparable type | a type that works with == (not slices, maps, funcs) |
Bill, Tip |
comparing uncomparable type / hash of unhashable type |
the panics from == / a map key on interfaces holding slices |
[]int in an any |
error |
the built-in interface interface{ Error() string } (episode 24) |
var err error = OutOfMilk{0} |
| Type assertion | getting the concrete value out of an interface (episode 22) | x.(int) |
Summary
- A parameter has one type; a concrete type like
Billwon't accept a*Khata. An interface type lists method signatures; any type with those methods satisfies it, with noimplementskeyword (implicit satisfaction, structural typing, checked by the compiler, unlike run-time duck typing). - Polymorphism: a
[]Totalerholds aBill, a*Khataand aTip, and one loop calls each one'sTotal. New types work without changing the loop. Method sets decide who fits: a pointer-receiver method means only&Tsatisfies (method Total has pointer receiver). - An interface value is a (dynamic type, dynamic value) pair, 16 bytes (itab/type word + data word). Storing a value copies it.
==compares both parts and panics on uncomparable dynamic types. - It is nil only when both parts are nil. Returning a nil
*Khataas aTotalergives a non-nil interface that panics later: returnnildirectly. interface{}/anyaccepts every type (fmt.Println(a ...any)) but has no methods:mismatched types any and int.fmt.Stringercontrols printing; a pointer-receiverString()is silently ignored for values.var _ Totaler = Bill{}andvar _ Totaler = (*Khata)(nil)check satisfaction at compile time, for free.erroris an interface too (episode 24).
Next episode: Type assertions, type switches and interface design: take the concrete value back out of an interface with t.(*Khata) and the comma-ok form, switch on its type, and design small interfaces like io.Reader.