Learnings

Go, part 3 of 5

Go Structs, Interfaces and Errors

How Go models data and behaviour without classes: structs, methods, embedding instead of inheritance, implicit interfaces, errors as values, panic and defer, and generics. One small bank runs through the whole page. Every program was run on Go 1.27 and the output under it is real.

Structs

Part 1 of 5 · data without classes

A struct is a typed group of fields. There are no classes, no constructors and no inheritance; the parts below show what Go uses instead.

Define, create, copy and compare

Structs

Create structs with named fields. A field you leave out gets its zero value, so a declared but unset struct is always usable. Assigning a struct copies every field.

  • Named fields always. Account{1, "x", 5} compiles, but breaks the day someone adds a field. go vet warns about it for types from other packages.
  • == compares field by field. It only compiles if every field is comparable. A slice or map field makes it a compile error: invalid operation: a == b (struct containing []int cannot be compared).
  • Python: a dataclass assignment shares the object; a Go struct assignment copies it. Use a pointer when you want sharing.

Anonymous structs

Structs

A struct type without a name, declared where it is used. Its main job in real code is the table of cases in a table-driven test, and one-off JSON shapes.

Struct tags and JSON

Structs

A tag is a string after a field that libraries read through reflection. encoding/json uses it for the key name and options. Only exported (capitalised) fields are encoded at all.

  • A lower-case field is silently skipped. This is the most common "my JSON is empty" bug.
  • json:"-" also blocks decoding, which is why the incoming PIN was ignored.
  • Unknown JSON keys are ignored by default. Use a json.Decoder with DisallowUnknownFields() to reject them.

Constructor functions

Structs

Go has no __init__. When a struct needs validation or defaults, write a plain function named NewX that returns the value, often with an error.

  • Name it NewAccount, or just New when the package has one main type (account.New).
  • Unexported fields plus a constructor is how you protect invariants: other packages cannot build an Account with a negative balance.
  • Better still, make the zero value useful so no constructor is needed. bytes.Buffer and sync.Mutex work as declared.

Defined types and aliases

Structs

type Rupees int creates a new, distinct type with int underneath. It does not mix with plain int without a conversion, and it can have methods. type Amount = int is an alias: another name for the very same type.

Without the conversion, r += n fails:

Interview line: defined types give type safety for free (you cannot pass a UserID where an AccountID is expected). Aliases exist for moving a type between packages without breaking callers; any is itself an alias for interface{}.

Enums with iota

Structs

Go has no enum keyword. Use a defined integer type, a const block where iota counts 0, 1, 2, and a String() method so it prints as a word.

  • The zero value is the first constant. If "not set" must be detectable, start with Unknown TxKind = iota.
  • There is no exhaustiveness check in switch, and any int converts. Validate input at the edges.
  • For long lists, go generate with the stringer tool writes String() for you.

Methods and embedding

Part 2 of 5 · behaviour on types, composition instead of inheritance

A method is a function with a receiver. Reuse comes from embedding one struct in another, which forwards fields and methods but does not create an "is a" relationship.

Value and pointer receivers

Methods and embedding

A value receiver gets a copy of the struct, so changes vanish when the method returns. A pointer receiver gets the address and can change the original. Python's self always behaves like a pointer receiver.

The first deposit was lost. The compiler does not warn: the code is legal, it just does nothing useful.

Which receiver to choose

Methods and embedding

SituationReceiver
The method changes the receiverPointer
The struct holds a sync.Mutex or other value that must not be copiedPointer
The struct is large (copying costs more than a pointer)Pointer
Small, immutable value type: Rupees, time.Time, a 2D pointValue
Map, func or channel type (already a reference)Value
Any other method on a type that already has pointer methodsPointer, to stay consistent

Rule of thumb: when in doubt, use a pointer receiver, and do not mix the two on one type. The only exception people make is String(), which is often a value receiver so both values and pointers print nicely.

Method sets and addressability

Methods and embedding

The method set of T holds its value-receiver methods; the method set of *T holds both kinds. Calling a pointer method on a variable works because Go can take the variable's address. Some values have no address: map elements, function results, literals.

Store pointers in the map (map[int]*Account) or copy the element out, change it, and write it back. The same rule matters again for interfaces.

Methods on any defined type

Methods and embedding

Methods are not limited to structs. Any type you define in your package can have them, including one based on int or a slice.

You cannot add methods to a type from another package, including built-in ones: func (i int) Double() int fails with cannot define new methods on non-local type int. Define your own type over it instead.

Method values

Methods and embedding

acc.Deposit without parentheses is a method value: a function with the receiver already bound, handy as a callback. (*Account).Deposit is a method expression: the receiver becomes the first argument.

Gotcha: a method value with a value receiver copies the receiver when it is created, so show() still sees the old balance. The same copy happens in defer acc.Show() and go acc.Show().

Embedding instead of inheritance

Methods and embedding

Put a type in a struct without a field name and its fields and methods are promoted: you can use them as if they were declared on the outer struct. Under the hood it is an ordinary field named after the type.

Python: class SavingsAccount(Account) says "is an Account"; Go embedding says "has an Account, and forwards its methods".

Shadowing a promoted method

Methods and embedding

Declare a method with the same name on the outer type and it hides the promoted one. The inner one is still reachable through the field. What does not happen is virtual dispatch: code inside Account always calls Account's methods.

Interview line: there is no "override" in Go. In Python, self.kind() inside the base class would call the subclass version; in Go the embedded value does not know it is embedded. When you need that behaviour, pass in an interface.

Embedding is not subtyping

Methods and embedding

A SavingsAccount is not an Account. A function that takes an Account will not accept one:

Two fixes: pass the embedded part (audit(s.Account)), or make audit take an interface that both types satisfy through the promoted methods. The second is the Go way to get polymorphism.

Embedding interfaces

Methods and embedding

An interface can embed other interfaces to combine them; this is how io.ReadWriter is built from io.Reader and io.Writer. A struct can embed an interface too, to wrap any implementation and change one method.

Careful: a struct that embeds an interface compiles even when the field is nil, and then panics on the first forwarded call. Always set it.

Interfaces

Part 3 of 5 · implicit, small, defined by the consumer

An interface is a set of method signatures. A type satisfies it by having those methods; nothing is declared. This is the main tool for polymorphism and testing in Go.

Implicit satisfaction

Interfaces

There is no implements keyword. If SMSNotifier has a Notify method with the right signature, it is a Notifier. It is Python's duck typing, checked by the compiler; the closest Python feature is typing.Protocol.

Because nothing is declared, a type written years ago in another package can satisfy an interface you write today, and that package never imports yours.

Small standard interfaces

Interfaces

The most used interfaces in Go have one method. Small interfaces are easy to satisfy, so many types do.

InterfaceMethodSatisfied by
io.ReaderRead(p []byte) (n int, err error)files, network connections, HTTP bodies, strings.Reader
io.WriterWrite(p []byte) (n int, err error)os.Stdout, files, strings.Builder, HTTP responses, hashes
fmt.StringerString() stringanything that wants to control how fmt prints it
errorError() stringevery error value
sort.InterfaceLen, Less, Swapolder sorting code; today use slices.SortFunc

A function that takes an io.Writer works with every destination at once:

Proverb: "The bigger the interface, the weaker the abstraction." Interfaces with one or two methods are the norm; an interface with ten methods usually means one implementation and a mock.

Accept interfaces, return structs

Interfaces

Functions take the smallest interface they need and return concrete types. The interface is declared by the code that uses it, next to that code, not by the package that implements it. Java and C# do the opposite, so this surprises people.

  • Returning a struct lets callers use every method and lets you add methods later without breaking anyone.
  • The consumer's one-method interface is trivial to fake in a test.
  • Do not create an interface "just in case" before there is a second implementation or a test that needs it.

What an interface value holds

Interfaces

An interface value is two words: the dynamic type of what is stored and the value (usually a pointer to it). An interface is nil only when both are empty.

Calls go through the method table of the stored type. An interface is nil only when the type word is empty too.

The nil interface gotcha

Interfaces

Store a nil pointer in an interface and the type word is set, so the interface is not nil. The classic version: a function that returns a typed nil pointer as an error.

Interview line: "When is an interface not equal to nil although it holds nil?" When it holds a typed nil pointer. Fix: never declare a variable of a concrete error type to return; return the literal nil on success.

any, type assertions and type switches

Interfaces

any is interface{}: it holds a value of any type. To get the concrete value back, use a type assertion v.(T) with the comma-ok form, or a type switch for several cases.

  • The one-value form n := v.(int) panics on a mismatch: panic: interface conversion: interface {} is string, not int. Use comma-ok unless a mismatch is a bug.
  • Cases are tried in order, so put specific interfaces before broad ones.
  • Reaching for any and type switches often is a smell. Generics (Part 5) or a real interface usually fit better.

Compile-time check

Interfaces

Since satisfaction is implicit, a typo in a method name is only noticed where the value is first used as the interface. This one line, next to the type, makes the compiler check it right there and costs nothing at run time:

(*EmailNotifier)(nil) is a nil pointer of the right type, and _ throws it away. Nothing is allocated.

Pointer receivers and interfaces

Interfaces

If Notify has a pointer receiver, only *EmailNotifier has it in its method set. Assigning a plain EmailNotifier value fails, because a value copied into an interface is not addressable:

Methods declared onvar n I = T{}var n I = &T{}
Value receiver (t T)CompilesCompiles
Pointer receiver (t *T)Compile errorCompiles

The fix is &EmailNotifier{}. This is the interface version of addressability.

Polymorphism

Interfaces

Several account types behind one interface. The loop does not know or care which concrete type it holds.

Dependency injection and fakes

Interfaces

Give a struct its dependencies as interface fields. Production passes the real thing; a test passes a ten-line fake. No mocking library is needed.

Errors, panic and defer

Part 4 of 5 · errors are values you return

Go has no exceptions for ordinary failures. A function that can fail returns an error as its last result, and the caller checks it. panic exists, but for bugs, not for control flow.

error, errors.New and fmt.Errorf

Errors, panic and defer

error is a built-in interface with one method, Error() string. errors.New makes a fixed one; fmt.Errorf formats one, and its %w verb wraps another error inside it so callers can still find it.

Both wrapped errors print the same text. The difference is invisible until someone asks "is this the insufficient funds error?", which is the next chapter.

Sentinel errors and errors.Is

Errors, panic and defer

A sentinel is a package-level error value, named ErrSomething, that callers compare against. Once it is wrapped, == fails; errors.Is walks the whole chain.

Each %w adds a link. errors.Is and errors.As follow the links; == only looks at the outermost one.

Standard library sentinels you will meet: io.EOF, sql.ErrNoRows, os.ErrNotExist, context.Canceled.

Custom error types and errors.As

Errors, panic and defer

When callers need data from an error, not just its identity, define a type with an Error() method. errors.As finds the first error in the chain of that type and fills in your variable. Go 1.26 added the generic errors.AsType, which returns it directly.

Caller needsUseCheck with
Only the messageerrors.New, fmt.Errorfnothing, just log or return it
To know which failureSentinel var ErrX = errors.New(...)errors.Is
Data about the failureCustom type with Error()errors.As or errors.AsType

errors.Join

Errors, panic and defer

Combine several errors into one, for example every validation failure at once. The result prints one error per line, and errors.Is matches any of them. errors.Join returns nil if all arguments are nil.

Wrap, handle once, and style

Errors, panic and defer

RuleWhy
Wrap with context: fmt.Errorf("load account %d: %w", id, err)The final message reads like a path: transfer: withdraw: insufficient funds
Return as is when you have nothing to addAvoids messages like error: error: failed: failed
Use %v instead of %w to hide an implementation detail%w makes the inner error part of your API: callers may start depending on sql.ErrNoRows
Handle an error once: either log it or return it, not bothLogging and returning prints the same failure at every layer
Error strings are lower case, no final full stopThey get joined: "load: Not Found." reads badly mid-sentence
Do not include the function's own name or "failed to"The caller's wrap already says what was being done
Check err before using the other resultsOn error, other results are usually zero values

panic and recover

Errors, panic and defer

A panic stops the function, runs its deferred calls, and unwinds the stack; if nothing recovers, the program crashes with a stack trace. recover() stops the unwinding, but only when called directly inside a deferred function.

Panic is right for programmer bugs and impossible states (index out of range, nil map write), and for setup that cannot fail in a correct program, such as regexp.MustCompile on a constant pattern. It is wrong for anything a user or network can cause.

Recover at a boundary, to turn a panic into an error so one bad request does not kill the server. net/http does exactly this for each request.

  • recover only catches panics in its own goroutine. A panic in another goroutine still crashes the program.
  • The named result err is what lets the deferred function change the return value. That trick is explained under defer.
  • Do not use panic and recover as try/except. Library code should return errors.

defer

Errors, panic and defer

defer f() runs f when the surrounding function returns, by any path, including a panic. Use it right after acquiring a resource: f, err := os.Open(p) then defer f.Close(); mu.Lock() then defer mu.Unlock().

  • Deferred calls run in reverse order, and their arguments are evaluated at the defer line, not at the end.
  • return nil sets err first, then deferred functions run and may change it. That only works with a named result.
  • defer inside a loop waits for the function to end, not the iteration. For many files, move the loop body into its own function.

Go errors vs Python exceptions

Errors, panic and defer

PythonGo
Normal failureraise InsufficientFunds()return fmt.Errorf("...: %w", ErrInsufficientFunds)
Handlingtry / except, possibly far up the stackif err != nil right after the call
Seeing what can failRead the docs or the sourceThe signature says so: (T, error)
Matching a kindexcept InsufficientFunds (class hierarchy)errors.Is (value) or errors.As (type)
Chainingraise X from e, __cause__%w, errors.Unwrap
Several at onceExceptionGroup, except*errors.Join
Cleanupfinally, withdefer
Crash for a bugUncaught exceptionpanic
Catch everythingexcept Exceptionrecover() in a deferred func, at boundaries only
Stack trace in the errorYes, automaticallyNo. Context comes from wrapping messages

Generics

Part 5 of 5 · type parameters, constraints, and when to skip them

Type parameters let one function or type work with many types while keeping compile-time checks. They arrived in Go 1.18, and Go 1.27 added type parameters on methods.

Generic functions: Map, Filter, Sum

Generics

Type parameters go in square brackets before the normal parameters. Each has a constraint that says what the type must support. The standard slices package has many helpers, but no Map or Filter, so people write these.

Constraints

Generics

A constraint is an interface. It can list methods, a union of types, or both. ~int means "any type whose underlying type is int", which is what lets Rupees through.

ConstraintAllowsLets you use
anyevery typeassign, pass, store; no operators
comparabletypes that support ====, !=, map keys
cmp.Orderedintegers, floats, strings<, >, plus ==
interface{ ~int | ~int64 }those types and types defined on themoperators all of them support: +, -, ...
interface{ String() string }types with that methodthe method

Drop the tilde (int | int64) and Rupees is rejected:

Generic types: Stack and Set

Generics

Types take type parameters too. Methods use the receiver's parameters: write (s *Stack[T]), not (s *Stack).

var zero T is the standard way to get "the zero value of whatever T is" for the not-found case.

Type inference

Generics

Go infers type arguments from the function's arguments, so you rarely write them. It cannot infer a type that appears only in the result; then you pass it in brackets.

Leaving out [Transaction] fails with in call to Parse, cannot infer T.

When not to use generics

Generics

If the function only calls methods on its argument, a plain interface parameter does the job and reads better.

  • Use generics for containers (stack, set, cache, tree) and for functions over slices, maps and channels of any element type, where the code is identical for every type.
  • Use an interface when each type behaves differently (each account computes its own month end).
  • Use neither when there is one concrete type today. Write the plain version first; generalise when the second type shows up.
  • Check the standard library first: slices, maps, cmp, built-in min and max already cover the common helpers.

What generics can and cannot do

Generics

Before Go 1.27 a method could not declare its own type parameters; a long-standing interview answer. Go 1.27 allows it. With go 1.26 in go.mod the same code fails with generic method requires go1.27 or later.

What still does not compile on Go 1.27, each line checked:

  • For the type switch, convert first: switch any(v).(type).
  • Because interfaces cannot declare generic methods, a generic method never helps a type satisfy an interface.
  • Constraints with unions (~int | ~int64) are for type parameters only. For a variable that holds "an int or a string", use any and a type switch.

Cheat sheet

Generics

The rules people most often get wrong, from the whole page.

TopicThe rule
Struct assignmentCopies every field. Use a pointer to share.
JSON fieldsOnly exported fields are encoded or decoded.
type A B vs type A = BNew distinct type vs another name for the same type.
Value receiverWorks on a copy; changes are lost.
Map elementsNot addressable: no pointer methods on m[k]; store pointers.
Method valuef := v.M copies a value receiver at that moment.
EmbeddingForwards fields and methods; no override, no virtual dispatch, not a subtype.
InterfacesSatisfied implicitly; keep them small; declare them where they are used.
Pointer receiver + interfaceOnly *T satisfies it: assign &T{}.
Nil interfaceAn interface holding a nil pointer is not nil. Return a literal nil.
Compile-time checkvar _ I = (*T)(nil)
Type assertionUse v, ok := x.(T); the one-value form panics.
Wrapping%w keeps the chain, %v hides it. Check with errors.Is / errors.As, not ==.
HandlingLog or return, never both. Lower-case messages.
panicFor bugs only. recover works only in a deferred call in the same goroutine.
deferLIFO; arguments evaluated at the defer line; can change named results.
Constraints~int includes defined types like Rupees; int alone does not.
Generic methodsAllowed from Go 1.27; interface methods still cannot be generic.

Next: Goroutines, Channels and Sync, running bank work concurrently and safely.