These are the notes for Go episode 22. In episode 21 one receipt printer learned to handle a Bill, a *Khata and a Tip through the Totaler interface. But an interface is a sealed box: it shows only its methods. Now Raju wants Asha's name on her khata line, and the compiler says no. Getting around that, you will invent the type assertion x.(T), see the interface conversion panic a wrong claim causes, fix it with the comma-ok assertion, and sort many types at once with a type switch. Then the episode turns to design: why a fat interface hurts, small interfaces, interface embedding (Reader + Writer = ReadWriter), the two most famous interfaces in Go, io.Reader and io.Writer, the rules "accept interfaces, return structs" and define interfaces at the consumer, the mistake called interface pollution, and a preview of error as an interface. The expert corner covers asserting to interface types, case order, the nil cases, writing your own io.Writer, what Read really does, and what an assertion costs. 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 0x... numbers (addresses and offsets) differ between machines and runs.
The problem: the box shows only its methods
Here is episode 21's Totaler, and Khata now has a Name field next to Owed. line takes a Totaler and tries to print the customer's name.
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 {
Name string
Owed float64
}
func (k *Khata) Total() float64 { return k.Owed }
func line(t Totaler) {
fmt.Println(t.Name, t.Total())
}
func main() {
line(&Khata{"Asha", 17.5})
}
# command-line-arguments
./main.go:19:19: t.Name undefined (type Totaler has no field or method Name)
- Recall from episode 21: a variable has a static type, the type written in its declaration, which never changes. Here
t's static type isTotaler. The value inside the interface right now has a dynamic type (here*Khata), the concrete type stored in the box while the program runs. A concrete type is a real type that says exactly how its data is stored, likeBill,*Khataorint. - The compiler checks every line using only the static type. All it knows about a
Totaleris "it has aTotal() float64method". It has no idea that a*Khata, with aNamefield, will be inside when the program runs. Sot.Nameis rejected:type Totaler has no field or method Name. - This is a feature, not a bug:
lineworks for anyTotaler, including aBill, which has noNameat all. But sometimes you really need the concrete value back. We need a way to say: "I believe this box holds a*Khata. Open it, and give me that pointer."
Type assertions: opening a sealed parcel
| A parcel at the door | In Go | Name |
|---|---|---|
| A sealed parcel: you only see the outside | t Totaler: contents hidden |
an interface value |
| "It's my new phone": you open it | k := t.(*Khata): claim the type, get the value |
a type assertion |
| It's someone else's shoes: your claim was wrong | the program crashes | a panic: interface conversion |
- A type assertion is an expression, written
x.(T), that claims the interface valuexholds a value of typeT. If the claim is true, its result is that value, with typeT: all its fields and methods are usable again. Readt.(*Khata)as "t, asserted to be a*Khata". xmust be an interface value.Tis the type you claim is inside; it is usually a concrete type (it can also be an interface type: see "Asserting to an interface type").- An expression is any piece of code that produces a value, like
2 + 3,t.Total()ort.(*Khata).
Your first type assertion
k := t.(*Khata) claims the box holds a *Khata. We call line with Asha's khata, then with a plain Bill.
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 {
Name string
Owed float64
}
func (k *Khata) Total() float64 { return k.Owed }
func line(t Totaler) {
k := t.(*Khata)
fmt.Println(k.Name, k.Total())
}
func main() {
line(&Khata{"Asha", 17.5})
line(Bill{67.5})
}
Asha 17.5
panic: interface conversion: main.Totaler is main.Bill, not *main.Khata
goroutine 1 [running]:
main.line({0x4da388?, 0xc00010af20?})
/tmp/.../main.go:19 +0xb4
main.main()
/tmp/.../main.go:25 +0x6c
exit status 2
Asha 17.5: for the khata, the claim was true,kis a real*Khata, andk.Nameworks.- For the
Bill, the claim was wrong, and the program panicked. A panic is a run-time crash that stops the program and prints a stack trace: the list of functions that were running, newest first, with file and line (herelineat line 19, called frommainat line 25). Episode 26 covers panics in depth. - Read the message slowly:
interface conversion: main.Totaler is main.Bill, not *main.Khatameans "the interface of static typeTotalerholds amain.Bill, but you asserted*main.Khata".main.is the package name in front of each type. - The assertion compares the dynamic type, the label on the box, and it must match exactly.
*Khatais notKhata, and neither isBill. There is no conversion and no "close enough". - So a plain assertion
x.(T)is safe only when you are certain of the type. Usually you aren't.
The comma-ok assertion: ask before you open
Ask with two results instead: k, ok := t.(*Khata). The second result ok is a bool (true or false): true if the claim was right. This is the comma-ok idiom, the same shape as a map lookup v, ok := m[key] from episode 15.
package main
import "fmt"
type Totaler interface{ Total() float64 }
type Bill struct{ Sum float64 }
type Khata struct {
Name string
Owed float64
}
func (b Bill) Total() float64 { return b.Sum }
func (k *Khata) Total() float64 { return k.Owed }
func line(t Totaler) {
if k, ok := t.(*Khata); ok {
fmt.Println("Khata of", k.Name, k.Total())
return
}
fmt.Println("Other", t.Total())
}
func main() {
line(&Khata{"Asha", 17.5})
line(Bill{67.5})
k, ok := Totaler(Bill{30}).(*Khata)
fmt.Println(k, ok)
}
Khata of Asha 17.5
Other 67.5
<nil> false
Khata of Asha 17.5for the khata,Other 67.5for the bill, and no panic. The two-result form never panics.- When the claim is wrong,
okisfalseandkis the zero value of the asserted type (episode 3: the value a variable gets when you don't set one). The zero value of a pointer type isnil, so the last line prints<nil> false. if k, ok := t.(*Khata); ok { ... }is an if with an init statement (episode 7):kandokexist only inside thatif. This is the most common way to write it.Totaler(Bill{30})is a conversion, not an assertion: it wraps aBillin aTotalerbox. We need it because you can only assert on an interface value. A plainBillhas no box to open:
b := Bill{30}
v, ok := b.(Bill)
# command-line-arguments
./main.go:9:14: invalid operation: b (variable of struct type Bill) is not an interface
The compiler rejects impossible claims
If a type can never be inside the interface, the compiler stops you before the program runs. With the same Totaler and pointer-receiver Khata, plus a Coupon with no Total method (real run, lines 18 and 19 were these):
var t Totaler = &Khata{"Asha", 17.5}
c := t.(Coupon)
k := t.(Khata)
# command-line-arguments
./main.go:18:10: impossible type assertion: t.(Coupon)
Coupon does not implement Totaler (missing method Total)
./main.go:19:10: impossible type assertion: t.(Khata)
Khata does not implement Totaler (method Total has pointer receiver)
- A
Couponhas noTotal, so it can never satisfyTotaler(episode 21: a type satisfies an interface when it has every method the interface lists). - A
Khatavalue can't either:Totalhas a pointer receiver(k *Khata), so it is only in the method set of*Khata(episode 20: the method set of a type is the list of methods callable on it through an interface). Onlyt.(*Khata)can ever succeed.
Assertions and nil
Two boxes from episode 21: the nil interface (no type, no value) and the typed nil (an interface holding a nil pointer). With the same Totaler and Khata (real run, line 24 is the last line):
var empty Totaler
k, ok := empty.(*Khata)
fmt.Println(k, ok)
var nk *Khata
var typed Totaler = nk
k, ok = typed.(*Khata)
fmt.Println(k, ok, k == nil)
k = empty.(*Khata)
<nil> false
<nil> true true
panic: interface conversion: main.Totaler is nil, not *main.Khata
goroutine 1 [running]:
main.main()
/tmp/.../main.go:24 +0xd4
exit status 2
- Comma-ok on a nil interface:
<nil> false. There is no label to match, so the claim fails. - On a typed nil:
okis true. The label really says*Khata; the pointer inside just happens to be nil. Sook == truedoes not meank != nil. Checkktoo if the producer might store nil pointers. - A plain assertion on a nil interface panics with
interface conversion: main.Totaler is nil, not *main.Khata.
Type switches: the sorting desk at a post office
Raju now has three kinds of lines: khata, bill and tip. One comma-ok check per type means a ladder of ifs. Think of a post office.
| Post office | In Go | Name |
|---|---|---|
| A pile of mixed parcels | []Totaler: many dynamic types |
a slice of interface values |
| The sorting desk reads each label once | switch v := t.(type) |
a type switch |
| Inside each bin you know what you hold | case *Khata:: here v is a *Khata |
the case's type |
- A type switch is a
switchstatement whose cases are types, not values. It looks at the dynamic type once and runs the first matching case. t.(type), with the keywordtypein the parentheses, is only allowed directly in a switch. Written anywhere else, likefmt.Println(x.(type)), it is a compile error:use of .(type) outside type switch.v := t.(type)declares a variablevthat, inside each case, already has that case's type.
package main
import "fmt"
type Totaler interface{ Total() float64 }
type Bill struct{ Sum float64 }
type Tip float64
type Khata struct {
Name string
Owed float64
}
func (b Bill) Total() float64 { return b.Sum }
func (t Tip) Total() float64 { return float64(t) }
func (k *Khata) Total() float64 { return k.Owed }
func line(t Totaler) {
switch v := t.(type) {
case *Khata:
fmt.Println("Khata of", v.Name, v.Owed)
case Bill, Tip:
fmt.Printf("%T %.2f\n", v, v.Total())
case nil:
fmt.Println("nothing here")
}
}
func main() {
line(&Khata{"Asha", 17.5})
line(Bill{67.5})
line(Tip(10))
line(nil)
}
Khata of Asha 17.5
main.Bill 67.50
main.Tip 10.00
nothing here
case *Khata:herevis a*Khata, sov.Nameandv.Owedwork: no separate assertion needed.case Bill, Tip:lists two types; it matches either.case nil:matches a nil interface (an empty box). Without it,line(nil)would match no case and print nothing.- A
default:case (none here) runs when nothing else matches, like in an ordinaryswitch. There is no fall-through between cases: exactly one case runs.
In a two-type case, v stays the interface
In case Bill, Tip: v can't be a Bill and a Tip at the same time, so it keeps the static type of the switched expression, Totaler. That's why the case above calls v.Total(), not v.Sum. %T still shows the dynamic type (main.Bill), because %T looks inside the box. Try v.Sum there (real run, line 15 was fmt.Println(v.Sum) inside case Bill, Tip:):
# command-line-arguments
./main.go:15:23: v.Sum undefined (type Totaler has no field or method Sum)
| Case | Type of v inside it |
|---|---|
case *Khata: (one type) |
*Khata |
case Bill, Tip: (several types) |
Totaler (the switched expression's type) |
case nil: and default: |
Totaler |
Type switches on any
Episode 21 ended with var x any = 3; x + 1 failing with mismatched types any and int. any is the empty interface interface{}, satisfied by every type. In a type switch over an any, each case hands you a real, typed value:
package main
import "fmt"
func describe(x any) string {
switch v := x.(type) {
case int:
return fmt.Sprint("int, doubled: ", v*2)
case string:
return "string of length " + fmt.Sprint(len(v))
case []int:
return fmt.Sprint("slice with ", len(v), " items")
default:
return fmt.Sprintf("something else: %T", v)
}
}
func main() {
fmt.Println(describe(3))
fmt.Println(describe("chai"))
fmt.Println(describe([]int{1, 2, 3}))
fmt.Println(describe(2.5))
}
int, doubled: 6
string of length 4
slice with 3 items
something else: float64
- In
case int:vis anint, sov*2just works. Incase string:it's astring; incase []int:a slice, solen(v)works. 2.5matched no case and fell todefault:, wherevis still anany;%Treportsfloat64.- This is how
fmtitself handles theanyvalues you pass toPrintln: inside thefmtpackage there is a type switch over the argument, with cases forbool,int,stringand so on.
Impossible cases
The compiler still guards you. A Coupon has no Total method, so it can never be inside a Totaler:
package main
import "fmt"
type Totaler interface{ Total() float64 }
type Coupon struct{ Code string }
func main() {
var t Totaler
switch t.(type) {
case Coupon:
fmt.Println("a coupon?")
}
}
# command-line-arguments
./main.go:12:10: impossible type switch case: Coupon
t (variable of interface type Totaler) cannot have dynamic type Coupon (missing method Total)
impossible type switch case: Coupon with the reason on the next line: t (variable of interface type Totaler) cannot have dynamic type Coupon (missing method Total). Exactly like the plain assertion t.(Coupon) above, Go rejects a claim that can never be true.
Assertion or switch? Three tools
| You want | Write | If the type is wrong |
|---|---|---|
| one type, and you are sure | v := x.(T) |
panic |
| one type, maybe | v, ok := x.(T) |
ok == false, v is the zero value |
| several types | switch v := x.(type) { case T1: ... } |
default: (or nothing) |
- ★
xmust always be an interface value. - ★
Tmay be a concrete type or another interface:if s, ok := x.(fmt.Stringer); ok { ... }asks "whatever is in here, does it have aString() stringmethod?"fmt.Stringer(episode 21) is the standard interfaceinterface{ String() string }. That's howfmtfinds yourStringmethod.
Asserting to an interface type
With an interface T, the assertion succeeds when the dynamic type satisfies T, not when it equals T. In a type switch, interface cases can match many types, and cases are tried top to bottom:
type Bill struct{ Sum float64 }
func (b Bill) String() string { return fmt.Sprintf("Bill(%.2f)", b.Sum) }
func kind(x any) string {
switch v := x.(type) {
case fmt.Stringer:
return "Stringer: " + v.String()
case Bill:
return "Bill" // never reached: a Bill is a Stringer
case error:
return "error: " + v.Error()
default:
return fmt.Sprintf("plain %T", v)
}
}
func main() {
fmt.Println(kind(Bill{30}))
fmt.Println(kind(fmt.Errorf("no milk")))
fmt.Println(kind(42))
}
Stringer: Bill(30.00)
error: no milk
plain int
Billhas aStringmethod, so it matchescase fmt.Stringer:first;case Bill:below is never reached for it. Put specific concrete types before broad interface cases.fmt.Errorf("no milk")makes anerrorvalue (more below), so it lands incase error:.42is a plainint.- In
case fmt.Stringer:vhas typefmt.Stringer, sov.String()is callable, whatever the concrete type is.
Interface design: why small interfaces win
Now, design. A teammate writes one big Shop interface with six methods. showTotal only needs Total. In a test you want a tiny fake: a stand-in type, written only for testing, that returns a fixed number instead of doing real work.
package main
import "fmt"
type Shop interface {
Total() float64
AddItem(name string, price float64)
Print()
Save() error
Email(to string) error
Close() error
}
type FakeShop struct{ total float64 }
func (f FakeShop) Total() float64 { return f.total }
func showTotal(s Shop) {
fmt.Println("Total:", s.Total())
}
func main() {
showTotal(FakeShop{99})
}
# command-line-arguments
./main.go:23:15: cannot use FakeShop{…} (value of struct type FakeShop) as Shop value in argument to showTotal: FakeShop does not implement Shop (missing method AddItem)
FakeShop does not implement Shop (missing method AddItem). To pass a fake, you'd have to write five useless methods:AddItem,Print,Save,Email,Close. The compiler names only the first missing one.- The bigger the interface, the fewer types can satisfy it, and the harder it is to reuse code that takes it.
- The fix is to ask for less.
showTotalonly callsTotal, so it should take aTotaler:
type Totaler interface{ Total() float64 }
type FakeShop struct{ total float64 }
func (f FakeShop) Total() float64 { return f.total }
func showTotal(t Totaler) {
fmt.Println("Total:", t.Total())
}
Total: 99
- A small interface is one with one or two methods. Rob Pike put it as a Go proverb (his "Go Proverbs" talk at Gopherfest SV 2015): "The bigger the interface, the weaker the abstraction." An abstraction is a simplified view that hides details: the less an interface demands, the more things it can stand for. Most interfaces in Go's standard library have one or two methods.
Interface embedding: a power strip built from sockets
What if something really needs two abilities?
| Electrical | In Go | Name |
|---|---|---|
| One socket does one job | Reader, Writer: one method each |
small interfaces |
| A strip combines sockets | type ReadWriter interface{ Reader; Writer } |
interface embedding |
| Plug into either socket | var r Reader = rw |
a ReadWriter is also a Reader |
- Interface embedding means listing another interface's name inside an interface's braces. The new interface gets all of that interface's methods.
ReadWriter= every method ofReader+ every method ofWriter. - You build big interfaces from small ones, instead of writing one big one.
package main
import "fmt"
type Reader interface{ Read() string }
type Writer interface{ Write(s string) }
type ReadWriter interface {
Reader
Writer
}
type Notebook struct{ pages []string }
func (n *Notebook) Write(s string) { n.pages = append(n.pages, s) }
func (n *Notebook) Read() string {
return fmt.Sprint(len(n.pages), " pages: ", n.pages)
}
func main() {
var rw ReadWriter = &Notebook{}
rw.Write("chai 10")
rw.Write("samosa 15")
var r Reader = rw // a ReadWriter is also a Reader
fmt.Println(r.Read())
}
2 pages: [chai 10 samosa 15]
Notebook's methods have pointer receivers (they changepages), so*NotebooksatisfiesReader,WriterandReadWriter; that's why we store&Notebook{}.var r Reader = rwassigns one interface to another. It compiles because everyReadWriterhas aReadmethod. The box is copied as is:rholds the same*Notebook, so it reads the two pages written throughrw.- The other direction does not compile, because a
Readermight not haveWrite:var rw ReadWriter = rgivescannot use r (variable of interface type Reader) as ReadWriter value in variable declaration: Reader does not implement ReadWriter (missing method Write). You'd need an assertion,r.(ReadWriter).
io.Reader and io.Writer: one standard pipe size
The real Reader and Writer live in Go's standard io package (short for input/output: data coming into or going out of a program).
| Plumbing | Package io | Name |
|---|---|---|
| A water source: tank, well or river | anything you can read bytes from | io.Reader |
| Where water goes: bucket, garden, sink | anything you can write bytes to | io.Writer |
| One standard pipe size: every fitting connects | files, network, strings, buffers | one method each |
From the standard library:
type Reader interface {
Read(p []byte) (n int, err error)
}
type Writer interface {
Write(p []byte) (n int, err error)
}
type ReadWriter interface {
Reader
Writer
}
- A byte is a number from 0 to 255 (8 bits). Text, images and everything else are stored as bytes; a string's text is stored as UTF-8 bytes (episode 17).
[]byteis a slice of bytes. Read(p)fills the slicepwith up tolen(p)bytes and returnsn, how many bytes it put there, anderr, an error (nil when all went well;io.EOFat the end of the data: "end of file").Write(p)takes the bytes inp, sends them somewhere, and returns how many it wrote and an error.io.ReadWriteris built by embedding, exactly like ourReadWriter.- Because the "pipe size" is standard, everything connects: files, network connections, strings, in-memory buffers, compressors, hash functions. Each satisfies one tiny interface, and code written for
io.Writerworks with all of them.
One function, three destinations
package main
import (
"bytes"
"fmt"
"io"
"os"
"strings"
)
func receipt(w io.Writer, total float64) {
fmt.Fprintf(w, "Total: Rs %.2f\n", total)
}
func main() {
receipt(os.Stdout, 67.5)
var sb strings.Builder
receipt(&sb, 17.5)
fmt.Print("builder got: ", sb.String())
var buf bytes.Buffer
receipt(&buf, 10)
fmt.Println("buffer has", buf.Len(), "bytes")
}
Total: Rs 67.50
builder got: Total: Rs 17.50
buffer has 16 bytes
fmt.Fprintf(w, ...)isPrintfthat writes to anyio.Writerwinstead of the terminal (the F stands for file).FprintlnandFprintexist too (episode 18).os.Stdoutis the program's standard output, normally the terminal. Its type,*os.File, has aWritemethod.fmt.Printlnitself writes toos.Stdout.strings.Buildercollects written bytes into a string efficiently;sb.String()gives the result. ItsWritehas a pointer receiver, so we pass&sb.bytes.Bufferis a growable box of bytes in memory that you can write to and read from.buf.Len()is how many unread bytes it holds:Total: Rs 10.00plus the newline is 16 bytes.receiptdoesn't know or care where the bytes go. Tomorrow, pass it a file or a network connection, unchanged.
The reading side
package main
import (
"fmt"
"io"
"os"
"strings"
)
func countBytes(r io.Reader) int {
data, _ := io.ReadAll(r)
return len(data)
}
func main() {
fmt.Println(countBytes(strings.NewReader("chai 10\nsamosa 15\n")))
f, err := os.Open("/etc/hostname")
if err != nil {
fmt.Println(err)
return
}
defer f.Close()
fmt.Println(countBytes(f) > 0)
}
18
true
io.ReadAll(r)keeps callingr.Readuntil the end (io.EOF) or an error, and returns everything it read as a[]byte.strings.NewReader(s)returns a*strings.Reader: anio.Readerthat reads from a string."chai 10\nsamosa 15\n"is 18 bytes (\n, the newline, is one byte).os.Open(path)opens a file for reading and returns a*os.File(anio.Reader) and an error.defer f.Close()(episode 10) closes the file whenmainreturns./etc/hostnameis a small text file on Linux; on a machine without it,os.Openreturns an error and the program prints it. We printcountBytes(f) > 0(true), because the file's size differs between machines.- One function reads from a string and from a file. Episode 33 goes deep into
ioandbufio.
Interface design rules
Three rules from experienced Go developers, and one mistake to avoid.
- Keep interfaces small: one or two methods, like
io.Reader. - Accept interfaces, return structs.
- Define an interface where it is used (the consumer), not where it is implemented (the producer).
Accept interfaces, return structs
- Parameters should be interfaces (as small as possible), so callers can pass anything that fits:
func receipt(w io.Writer, ...). - Results should be concrete types, usually a struct or a pointer to one:
func NewKhata(name string) *Khata. The caller gets every field and method, and can still pass the result on as any interface it satisfies. IfNewKhatareturned aTotaler, the caller would loseNameandAddand need an assertion to get them back: today's whole problem. - A constructor is an ordinary function, by convention named
NewX, that creates and returns a ready-to-useX.
Define interfaces at the consumer
- The producer is the code (usually a package: a folder of Go files that is compiled together, episode 27) that implements a type, like a
khatapackage withKhata. The consumer is the code that uses values of that type, like areceiptpackage that prints totals. - In Java, the producer usually declares the interface, because a class must name it (
implements). In Go, satisfaction is implicit (episode 21), so the producer doesn't need to know any interface exists. The consumer declares exactly the methods it needs, often unexported (lowercase, visible only inside its own package).
One file, with comments marking the two sides:
package main
import "fmt"
// ---- the "producer": code that makes khatas (imagine package khata) ----
type Khata struct {
Name string
Owed float64
}
// NewKhata returns a concrete type: callers get every field and method.
func NewKhata(name string) *Khata { return &Khata{Name: name} }
func (k *Khata) Add(amount float64) { k.Owed += amount }
func (k *Khata) Total() float64 { return k.Owed }
// ---- the "consumer": code that prints totals (imagine package receipt) ----
// totaler is declared HERE, where it is used, with only what we need.
type totaler interface{ Total() float64 }
func showTotal(t totaler) { fmt.Printf("Total: Rs %.2f\n", t.Total()) }
// a test fake needs one method, not six
type fakeTotal float64
func (f fakeTotal) Total() float64 { return float64(f) }
func main() {
k := NewKhata("Asha")
k.Add(17.5)
k.Add(12.5)
fmt.Println(k.Name, "owes", k.Owed)
showTotal(k)
showTotal(fakeTotal(99))
}
Asha owes 30
Total: Rs 30.00
Total: Rs 99.00
NewKhatareturns*Khata(a concrete type), somainusesk.Name,k.Addandk.Owedfreely.showTotalaccepts the consumer's own one-methodtotaler. The real*Khatafits, and so does a one-line test fake. The producer never mentionedtotaler.
Interface pollution
Interface pollution is creating interfaces that nothing needs yet: an interface for every type, written "just in case", before a second implementation or a test exists. It adds a layer of indirection, an extra name and a place to keep in sync, with no benefit.
| ✗ Pollution | ✓ Go style |
|---|---|
type KhataService interface { ... 8 methods ... } next to its only implementation |
start with the concrete *Khata |
constructor returns the interface: func NewKhata() KhataService |
return the struct: func NewKhata() *Khata |
| every consumer must accept all 8 methods | each consumer declares the 1-2 methods it uses |
- Start concrete. Add an interface when a real need appears: a second implementation, a test fake, or a function that should work with several types. Because satisfaction is implicit, adding it later doesn't change the producer at all.
error is an interface (preview)
Every err you've checked so far had an interface type. error is a built-in interface (no import needed) with one method:
type error interface {
Error() string
}
Any type with an Error() string method is an error. OutOfStock has one.
package main
import "fmt"
type OutOfStock struct{ Item string }
func (e OutOfStock) Error() string {
return e.Item + " is out of stock"
}
func order(item string) error {
if item == "samosa" {
return OutOfStock{item}
}
return nil
}
func main() {
err := order("samosa")
fmt.Println(err)
if e, ok := err.(OutOfStock); ok {
fmt.Println("restock:", e.Item)
}
fmt.Println(order("chai"))
}
samosa is out of stock
restock: samosa
<nil>
samosa is out of stock:Printlnfound that the value is anerrorand called itsErrormethod.err.(OutOfStock), a comma-ok assertion, got theOutOfStockstruct back, so we know which item to restock. That's today's tool applied to errors.order("chai")returnednil: a nil interface, "no error". Remember the typed-nil trap from episode 21: return a literalnil, never a nil pointer of your error type.- Episode 24 is all about errors; episode 25 shows
errors.As, which does this assertion even when the error has been wrapped inside another error.
Expert corner
The compiler polices type switches too
switch v := x.(type)where no case usesvfails withv declared and not used, as any unused variable does. Writeswitch x.(type)(nov :=) when you only need to know the type.fallthrough(jump into the next case, episode 7) is forbidden in a type switch, since the next case'svwould have a different type:cannot fallthrough in type switch. A type listed twice givesduplicate case Bill in type switch, followed by the position of theprevious case.
Writing your own io.Writer: delegation
Any type with Write(p []byte) (int, error) is an io.Writer, so every fmt.Fprint* function works with it. ByteCounter counts bytes and delegates the real writing to another writer. Delegation means a type handing a job over to another value it holds, here the io.Writer in its W field.
package main
import (
"fmt"
"io"
"os"
)
// ByteCounter counts the bytes written to it and passes them on.
type ByteCounter struct {
W io.Writer
N int
}
func (c *ByteCounter) Write(p []byte) (int, error) {
n, err := c.W.Write(p)
c.N += n
return n, err
}
var _ io.Writer = (*ByteCounter)(nil)
func main() {
c := &ByteCounter{W: os.Stdout}
fmt.Fprintf(c, "chai %d\n", 10)
fmt.Fprintln(c, "samosa", 15)
fmt.Println("bytes written:", c.N)
}
chai 10
samosa 15
bytes written: 18
var _ io.Writer = (*ByteCounter)(nil)is episode 21's compile-time check: the build fails right here ifWrite's signature is ever wrong."chai 10\n"is 8 bytes and"samosa 15\n"10: 18 in all. Wrappers like this, anio.Writerthat wraps anotherio.Writer, are everywhere in the standard library (compressors, hashes,io.MultiWriter).
What Read really does
Read gives you at most len(p) bytes per call, and signals the end with io.EOF. With import ("fmt"; "io"; "strings"):
func main() {
r := strings.NewReader("chai 10\n")
buf := make([]byte, 3)
for {
n, err := r.Read(buf)
fmt.Printf("n=%d %q err=%v\n", n, buf[:n], err)
if err == io.EOF {
break
}
}
}
n=3 "cha" err=<nil>
n=3 "i 1" err=<nil>
n=2 "0\n" err=<nil>
n=0 "" err=EOF
- A 3-byte buffer reads
"chai 10\n"in pieces: 3, 3, 2, then0bytes andEOF. Always usep[:n], never all ofp: the bytes afternare left over from earlier calls. io.EOFis not a failure; it means "no more data". Theiodocs allow a reader to return the last bytes andio.EOFin the same call, so processnbytes before checkingerr.io.ReadAlldoes this loop for you.
Optional abilities: asserting one interface to another
w.(io.Reader) on an io.Writer asks "can this writer also read?" With import ("bytes"; "fmt"; "io"; "strings"):
func main() {
for _, w := range []io.Writer{&bytes.Buffer{}, &strings.Builder{}} {
_, canRead := w.(io.Reader)
fmt.Printf("%-16T can read: %v\n", w, canRead)
}
}
*bytes.Buffer can read: true
*strings.Builder can read: false
A *bytes.Buffer has both Read and Write; a *strings.Builder only writes. Standard library code uses exactly this pattern to look for optional extra abilities on a value (for example io.Copy checks whether its source has a WriteTo method, the io.WriterTo interface) and takes a faster path when they exist.
What an assertion costs
Recall episode 21: an interface value is two words, a type word and a data word. In Go's standard compiler, an assertion to a concrete type (t.(*Khata), or a concrete case in a type switch) compares the type word with the one for *Khata: a single comparison, very cheap. An assertion to an interface type (x.(fmt.Stringer)) must check that the dynamic type has the needed methods; the runtime caches that answer, so repeated checks are fast too. Neither is a reason to avoid assertions. The reason to prefer methods is design: the type switch in printReceipt below must be edited whenever Raju adds a kind of line, while a Label() string method on the interface would travel with each new type. Use a type switch when the set of types is fixed or comes from outside (any values from decoding, errors), and methods for your own growing family of types.
Mini project: a receipt printer that writes anywhere
printReceipt now takes an io.Writer and any number of Totalers (a variadic parameter, items ...Totaler, episode 9). Inside the loop, a type switch picks the label: the name for a khata, Tip for a tip, and Bill as the default (set before the switch).
package main
import (
"fmt"
"io"
"os"
)
type Totaler interface{ Total() float64 }
type Bill struct{ Sum float64 }
type Tip float64
type Khata struct{ Name string; Owed float64 }
func (b Bill) Total() float64 { return b.Sum }
func (t Tip) Total() float64 { return float64(t) }
func (k *Khata) Total() float64 { return k.Owed }
func printReceipt(w io.Writer, items ...Totaler) {
for _, t := range items {
label := "Bill"
switch v := t.(type) {
case *Khata:
label = "Khata:" + v.Name
case Tip:
label = "Tip"
}
fmt.Fprintf(w, "%-11s %6.2f\n", label, t.Total())
}
}
func main() {
printReceipt(os.Stdout, Bill{67.5}, &Khata{"Asha", 17.5}, Tip(10))
}
Bill 67.50
Khata:Asha 17.50
Tip 10.00
Khata:Asha: the name we couldn't reach at the start of the episode, now reached with a type switch.printReceiptwrites withfmt.Fprintf(w, ...), so it can print to the terminal, astrings.Builder, a file or a network connection. Pause and add a running total and aTotalline (the extended version below has one), then send it to astrings.Builderand printsb.String().type Khata struct{ Name string; Owed float64 }is written on one line to fit the screen;gofmtwould spread the two fields over separate lines. Both mean exactly the same.- The format
%-11s %6.2f(episode 18) left-aligns the label in 11 characters and right-aligns the amount in 6 with two decimals.
Extended version: table numbers, phone numbers, a Stringer fallback and two destinations at once
Episode 21 promised Asha's phone number on khata lines. Bills now carry a table number, a new Delivery type falls into a fmt.Stringer case, and io.MultiWriter (standard library) returns one io.Writer that copies every write to all the writers you give it: here the terminal and a saved copy in a strings.Builder.
package main
import (
"fmt"
"io"
"os"
"strings"
)
type Totaler interface{ Total() float64 }
type Bill struct {
Table int
Sum float64
}
type Tip float64
type Khata struct {
Name string
Phone string
Owed float64
}
type Delivery struct{ Fee float64 }
func (b Bill) Total() float64 { return b.Sum }
func (t Tip) Total() float64 { return float64(t) }
func (k *Khata) Total() float64 { return k.Owed }
func (d Delivery) Total() float64 { return d.Fee }
func (d Delivery) String() string { return "Delivery" }
func printReceipt(w io.Writer, items ...Totaler) {
var sum float64
for i, t := range items {
label, note := "", ""
switch v := t.(type) {
case *Khata:
label = "Khata: " + v.Name
note = "call " + v.Name + " at " + v.Phone
case Bill:
label = fmt.Sprintf("Table %d", v.Table)
case Tip:
label = "Tip"
case fmt.Stringer:
label = v.String()
default:
label = fmt.Sprintf("%T", v)
}
fmt.Fprintf(w, "%2d. %-12s %8.2f\n", i+1, label, t.Total())
if note != "" {
fmt.Fprintf(w, " (%s)\n", note)
}
sum += t.Total()
}
fmt.Fprintln(w, " -----------------------")
fmt.Fprintf(w, " %-12s %8.2f\n", "Total", sum)
}
func main() {
var saved strings.Builder
both := io.MultiWriter(os.Stdout, &saved)
printReceipt(both, Bill{4, 67.5}, &Khata{"Asha", "98xxxxxx01", 17.5}, Tip(10), Delivery{25})
fmt.Println("saved copy:", saved.Len(), "bytes,", strings.Count(saved.String(), "\n"), "lines")
}
1. Table 4 67.50
2. Khata: Asha 17.50
(call Asha at 98xxxxxx01)
3. Tip 10.00
4. Delivery 25.00
-----------------------
Total 120.00
saved copy: 188 bytes, 7 lines
case *Khata:usesv.Nameandv.Phone;case Bill:usesv.Table. Single-type cases give typedvs.Deliveryisn't listed by name; it lands incase fmt.Stringer:because it hasString(). Any future type with aStringmethod will too. A type with neither would print its type name throughdefault:.- The receipt appeared on the screen, and the same 188 bytes (7 lines) were saved:
printReceiptnever knew there were two destinations. - Try it: add
case Tip:aftercase fmt.Stringer:and giveTipaStringmethod; which case runs?
The next problem: Raju wants a Counter type that has everything a Bill has, plus fields of its own, without copying Bill's fields and methods. Go has no inheritance (a class automatically getting another class's fields and methods, as in Java). So how? Next episode: embedding and composition.
Common mistakes (and the real messages)
| You wrote | Real error / what happens | Fix |
|---|---|---|
t.Name where t is a Totaler |
t.Name undefined (type Totaler has no field or method Name) |
if k, ok := t.(*Khata); ok { k.Name } |
k := t.(*Khata) when t holds a Bill |
panic: interface conversion: main.Totaler is main.Bill, not *main.Khata |
comma-ok or a type switch |
k := t.(*Khata) when t is a nil interface |
panic: interface conversion: main.Totaler is nil, not *main.Khata |
comma-ok; check for nil |
t.(Khata) with a pointer-receiver Total |
impossible type assertion: t.(Khata) / Khata does not implement Totaler (method Total has pointer receiver) |
t.(*Khata) |
t.(Coupon) (no Total method) |
impossible type assertion: t.(Coupon) / Coupon does not implement Totaler (missing method Total) |
assert only types that can be inside |
b.(Bill) where b is a Bill |
invalid operation: b (variable of struct type Bill) is not an interface |
you already have the concrete value |
switch t.(type) { case Coupon: } |
impossible type switch case: Coupon / t (variable of interface type Totaler) cannot have dynamic type Coupon (missing method Total) |
only types that satisfy it |
v.Sum in case Bill, Tip: |
v.Sum undefined (type Totaler has no field or method Sum) |
one type per case, or use methods |
switch v := x.(type) but no case uses v |
v declared and not used |
switch x.(type) |
fallthrough in a type switch |
cannot fallthrough in type switch |
repeat the code, or list both types in one case |
| the same type in two cases | duplicate case Bill in type switch |
remove one |
case fmt.Stringer: before case Bill: |
no error: Bill never reaches its own case |
concrete cases first |
k, ok := t.(*Khata) then k.Name |
if t holds a nil *Khata, ok is true and k.Name panics |
also check k != nil |
a 6-method Shop for a function that calls one |
FakeShop does not implement Shop (missing method AddItem) |
small, consumer-side interfaces |
fmt.Fprintf(sb, ...) with var sb strings.Builder |
cannot use sb (variable of struct type strings.Builder) as io.Writer value in argument to fmt.Fprintf: strings.Builder does not implement io.Writer (method Write has pointer receiver) |
pass &sb |
var rw ReadWriter = r (r a Reader) |
Reader does not implement ReadWriter (missing method Write) |
rw, ok := r.(ReadWriter) |
err.(NoTable) when Error has a pointer receiver |
impossible type assertion: err.(NoTable) / NoTable does not implement error (method Error has pointer receiver) |
err.(*NoTable) |
fmt.Println(x.(type)) |
use of .(type) outside type switch |
only in switch |
| a constructor returning an interface | callers lose fields and need assertions | return the concrete type |
Every message above is from a real run (the code for each appears earlier in these notes, or is the one-line change shown).
Practice
- (Homework) Make a
[]anywith an int, a string, a bool, a[]string, aniland a float64. Writedescribe(x any) stringwith a type switch that describes each one (square the int, upper-case the string withstrings.ToUpper, join the list withstrings.Join). - (Homework) Write
report(w io.Writer, sold map[string]int)that prints a small sales report, and call it withos.Stdoutand with astrings.Builder. - (Homework) Make a custom error type
NoTable{No int}with a pointer-receiverError().seat(table int) errorreturns it for tables outside 1 to 8. Inmain, assert it back with comma-ok and print the table number. - Predict:
var t Totaler = Bill{30}; b, ok := t.(Bill); p, ok2 := t.(*Bill); fmt.Println(b, ok, p, ok2)(withBill'sTotalon a value receiver). - Which design rule does each break? (a)
func NewStall() StallServicewith an 8-method interface and one implementation. (b)func save(f *os.File)that only callsf.Write. (c) akhatapackage that declarestype Printer interface{...}"for the receipt package to use".
Solution
- In
case nil:the switch catches the nil interface;2.5falls todefault. Withimport ("fmt"; "strings"):
func describe(x any) string {
switch v := x.(type) {
case int:
return fmt.Sprintf("int %d, squared %d", v, v*v)
case string:
return fmt.Sprintf("string %q, upper %s", v, strings.ToUpper(v))
case bool:
if v {
return "bool: yes"
}
return "bool: no"
case []string:
return "list: " + strings.Join(v, ", ")
case nil:
return "nothing"
default:
return fmt.Sprintf("unknown %T", v)
}
}
func main() {
things := []any{7, "chai", true, []string{"tea", "bun"}, nil, 2.5}
for _, x := range things {
fmt.Println(describe(x))
}
}
int 7, squared 49
string "chai", upper CHAI
bool: yes
list: tea, bun
nothing
unknown float64
reporttakes anio.Writer, prints a header withfmt.Fprintln(w, "Sales report"), then onefmt.Fprintf(w, "%-7s %3d\n", item, sold[item])per item. Called withos.Stdout, then with&sbfollowed byfmt.Printf("builder: %d bytes, %q...\n", sb.Len(), sb.String()[:12]), a real run prints ("Sales report\n"is 13 bytes and each item line 12: 37 in all):
Sales report
chai 42
samosa 17
builder: 37 bytes, "Sales report"...
Errorhas a pointer receiver, so*NoTableis the error type: return&NoTable{table}and asserterr.(*NoTable). Assertingerr.(NoTable)would be an impossible type assertion.
type NoTable struct{ No int }
func (e *NoTable) Error() string { return fmt.Sprintf("table %d does not exist", e.No) }
func seat(table int) error {
if table < 1 || table > 8 {
return &NoTable{table}
}
return nil
}
func main() {
for _, t := range []int{3, 12} {
err := seat(t)
if err == nil {
fmt.Println("seated at", t)
continue
}
fmt.Println("error:", err)
if nt, ok := err.(*NoTable); ok {
fmt.Println("asked for table", nt.No, "- we have 1 to 8")
}
}
}
seated at 3
error: table 12 does not exist
asked for table 12 - we have 1 to 8
-
Real output
{30} true <nil> false: the box holds aBillvalue, sot.(Bill)succeeds.*Billalso satisfiesTotaler(a value-receiver method is in both method sets), sot.(*Bill)compiles, but the label saysBill, not*Bill:ok2is false andpis a nil*Bill. -
(a) Interface pollution and "return structs": return
*Stall, and let consumers declare small interfaces when they need them. (b) "Accept interfaces": takew io.Writer, so abytes.Bufferorstrings.Builderworks in tests. (c) "Define at the consumer": thereceiptpackage should declare the interface it needs;khatadoesn't need to know.
Quick quiz
1. What does this print? (From the video.)
var x any = 42
s, ok := x.(string)
fmt.Printf("%q %v\n", s, ok)
switch v := x.(type) {
case int:
fmt.Println(v + 1)
default:
fmt.Println("other")
}
A. "" false, then 43 · B. panic · C. "42" true, then 43 · D. "" false, then other
Answer
A. The comma-ok form never panics: s is the zero string "" (%q prints it quoted) and ok is false. In the type switch, x holds an int, so v is an int and v + 1 is 43. Real output:
"" false
43
2. In switch v := t.(type) { case Bill, Tip: ... } with t a Totaler holding Tip(10), what is the static type of v, and what does fmt.Printf("%T", v) print?
Answer
v is a Totaler (a case with several types keeps the switched expression's type), so v.Sum wouldn't compile. %T looks inside the box and prints main.Tip. Real run of fmt.Printf("%T %v\n", v, again == t) with var again Totaler = v: main.Tip true.
3. var t Totaler (never assigned). What does k, ok := t.(*Khata); fmt.Println(k, ok) print? And k := t.(*Khata)?
Answer
<nil> false, and the plain form panics: interface conversion: main.Totaler is nil, not *main.Khata.
4. Khata's Total has a pointer receiver. Does k, ok := t.(Khata) compile?
Answer
No: impossible type assertion: t.(Khata) / Khata does not implement Totaler (method Total has pointer receiver). A Khata value can never be inside a Totaler.
5. type ReadWriter interface{ Reader; Writer }. Which compiles: var r Reader = rw or var rw ReadWriter = r?
Answer
var r Reader = rw: every ReadWriter has Read. The other needs an assertion, rw, ok := r.(ReadWriter), because a Reader may not have Write.
Interview questions
1. What is a type assertion, and what happens when it fails?
x.(T) claims that the interface value x holds a T and returns it as a T. For a concrete T, the dynamic type must be exactly T; for an interface T, the dynamic type must satisfy T. The one-result form panics on failure (interface conversion: main.Totaler is main.Bill, not *main.Khata); the comma-ok form v, ok := x.(T) returns the zero value and false instead. The compiler rejects assertions that can never succeed (impossible type assertion) and assertions on non-interface values (is not an interface).
2. Type switch vs a chain of comma-ok assertions?
A type switch switch v := x.(type) checks the dynamic type once, picks the first matching case top to bottom, and gives v the case's type in single-type cases (the interface type in multi-type cases, nil and default). It's clearer and handles nil with case nil. fallthrough isn't allowed, and duplicate or impossible cases are compile errors.
3. When should you use type assertions at all?
When the set of types is open or external (any values from decoding, errors, optional capabilities like checking x.(fmt.Stringer) or w.(io.ReaderFrom)), or to get a concrete error type back (errors.As for wrapped errors). For your own growing family of types, prefer a method on the interface; a type switch must be edited every time a type is added.
4. Why are io.Reader and io.Writer considered great interface design?
Each has one method on []byte, so almost anything can implement them: files, network connections, buffers, strings, compressors, hashes. Code written once against io.Writer (like fmt.Fprintf) works with all of them, and wrappers (io.MultiWriter, counting writers) compose freely. Larger interfaces like io.ReadWriter are built by embedding them.
5. Explain "accept interfaces, return structs".
Parameters should be the smallest interface the function needs, so callers and tests can pass any fitting value. Results should be concrete types, so callers get all fields and methods without assertions, and can still assign the result to any interface it satisfies. Returning an interface hides capabilities and forces the producer to choose an interface for everyone.
6. Where should an interface be defined, and what is interface pollution?
In the consumer package that uses it, listing only the methods it calls; Go's implicit satisfaction means the producer needn't import or know about it. Interface pollution is declaring interfaces before they're needed (one per type, big, next to their only implementation), which adds indirection without benefit. Start concrete; extract an interface when a second implementation or a test needs one.
7. A function returns error. How do you get your custom error type back?
error is the built-in interface interface{ Error() string }, so use a comma-ok assertion if e, ok := err.(OutOfStock); ok { ... } (asserting the pointer type if Error has a pointer receiver), or a type switch. When errors may be wrapped by other errors, use errors.As, which searches the whole chain (episode 25). And never return a nil pointer of your error type as an error: it's a non-nil interface.
Glossary
| Term | Meaning | Example |
|---|---|---|
| Static type | the declared type of a variable; never changes; the compiler checks code with it | t Totaler |
| Dynamic type | the concrete type stored in an interface right now (episode 21) | *main.Khata |
| Concrete type | a real type that says exactly how data is stored | Bill, *Khata, int |
| Interface value | the (dynamic type, dynamic value) pair an interface variable holds | var t Totaler = Bill{67.5} |
| Expression | a piece of code that produces a value | t.(*Khata), 2 + 3 |
Type assertion x.(T) |
claims interface value x holds a T and returns it as a T; panics if wrong |
k := t.(*Khata) |
| Comma-ok assertion | the two-result form; ok reports success, never panics |
k, ok := t.(*Khata) |
| Comma-ok idiom | a second bool result saying whether something worked or existed | v, ok := m[key] |
| Panic | a run-time crash that stops the program with a stack trace (episode 26) | interface conversion |
| Stack trace | the list of running functions, with files and lines, printed by a panic | main.line(...) |
| Interface conversion panic | the panic from a failed one-result assertion | main.Totaler is main.Bill, not *main.Khata |
| Impossible type assertion | a compile error: the type can never be inside that interface | t.(Coupon) |
| Conversion | turning a value into another type; to an interface type, it boxes the value | Totaler(Bill{30}) |
| Zero value | the value a variable has when not set: 0, "", false, nil |
failed assertion's v |
| Typed nil | an interface holding a nil pointer; not == nil; assertion to its type gives ok == true |
var nk *Khata; var t Totaler = nk |
| Type switch | a switch whose cases are types: switch v := x.(type) |
case *Khata: |
.(type) |
the switch-only form that asks for the dynamic type | switch t.(type) |
case nil |
the type switch case matching a nil interface | line(nil) |
| Impossible type switch case | a compile error: a case type can't be in the interface | case Coupon: |
any |
alias for the empty interface interface{}; every type satisfies it |
func describe(x any) |
fmt.Stringer |
interface{ String() string }; fmt uses it to print |
x.(fmt.Stringer) |
| Satisfy / implement | to have every method an interface lists (episode 21) | *Khata satisfies Totaler |
| Method set | the methods callable on a type through an interface (episode 20) | Khata lacks pointer-receiver Total |
| Fake (test double) | a small stand-in type written for testing | FakeShop{99} |
| Small interface | an interface of one or two methods | Totaler, io.Reader |
| Abstraction | a simplified view that hides details | "something with a Total" |
| Interface embedding | listing an interface inside another to include all its methods | ReadWriter{ Reader; Writer } |
| Package | a folder of Go files compiled together; imported by path (episode 27) | io, os, strings |
io package |
Go's standard package for input and output | io.Reader, io.ReadAll |
| Byte | a number from 0 to 255 (8 bits); data is stored as bytes | []byte("chai") |
io.Reader |
Read(p []byte) (n int, err error): anything you can read bytes from |
strings.NewReader, *os.File |
io.Writer |
Write(p []byte) (n int, err error): anything you can write bytes to |
os.Stdout, &sb, &buf |
io.ReadWriter |
Reader and Writer embedded together |
*bytes.Buffer, *os.File |
io.EOF |
the error Read returns at the end of the data |
n=0 "" err=EOF |
io.ReadAll |
reads from a Reader until EOF; returns all the bytes | io.ReadAll(r) |
io.MultiWriter |
one Writer that copies each write to several Writers | io.MultiWriter(os.Stdout, &saved) |
fmt.Fprintf |
Printf to any io.Writer |
fmt.Fprintf(w, "Total: ...") |
os.Stdout |
the program's standard output, normally the terminal | receipt(os.Stdout, 67.5) |
strings.Builder |
builds a string from writes | sb.String() |
bytes.Buffer |
a growable in-memory byte box you can write and read | buf.Len() |
| Delegation | a type handing a job to another value it holds | ByteCounter calls c.W.Write |
| Constructor | a NewX function that creates a ready-to-use X |
NewKhata("Asha") |
| Accept interfaces, return structs | parameters as small interfaces, results as concrete types | receipt(w io.Writer), NewKhata() *Khata |
| Producer / consumer | the code that implements a type / the code that uses it | khata / receipt |
| Consumer-side interface | an interface declared where it's used, with only the needed methods | type totaler interface{ Total() float64 } |
| Interface pollution | interfaces created before any need for them | 8-method KhataService with one implementation |
| Unexported | a lowercase name, visible only inside its package (episode 27) | totaler |
error |
the built-in interface interface{ Error() string } (episode 24) |
OutOfStock |
errors.As |
finds an error of a given type in a wrapped chain (episode 25) | errors.As(err, &target) |
| Inheritance | getting another type's fields and methods automatically (not in Go; episode 23) | Java extends |
Summary
- Through an interface, the compiler sees only its methods (the static type):
t.Name undefined (type Totaler has no field or method Name). - A type assertion
x.(T)claims the dynamic type and returns the concrete value. A wrong claim panics:interface conversion: main.Totaler is main.Bill, not *main.Khata. The comma-ok formv, ok := x.(T)never panics:okis false andvthe zero value. Assertions need an interface value, and impossible ones are compile errors. - A type switch
switch v := x.(type)sorts many types in one place;vhas the case's type in single-type cases and stays the interface in multi-type cases.case nilcatches an empty box; interface cases match by satisfaction, top to bottom. - Small interfaces win ("the bigger the interface, the weaker the abstraction"). Interface embedding builds bigger ones from small ones:
io.ReadWriter=io.Reader+io.Writer, one[]bytemethod each, connecting files, strings, buffers and the terminal. - Accept interfaces, return structs; define interfaces at the consumer; avoid interface pollution: start concrete and add an interface when a need appears.
erroris justinterface{ Error() string }, and comma-ok gets your error type back (episodes 24 and 25).
Next episode: Embedding and composition: struct embedding, promoted fields and methods, and why Go chose composition over inheritance.