Go Intermediate for Confirmed Developers: Interfaces, Goroutines
Intermediate Go for confirmed developers: interfaces, error wrapping, goroutines and channels, sync and context, generics, modules and testing, with quizzes.
Study this lesson with its quizzes on Brainbotox →
Go interfaces, type assertions and type switches
A Go interface is a set of method signatures, and a type satisfies it implicitly simply by having those methods. There is no implements keyword.
Implicit satisfaction
type Shape interface {
Area() float64
}
type Circle struct{ R float64 }
func (c Circle) Area() float64 { return math.Pi * c.R * c.R }
var s Shape = Circle{R: 2} // Circle satisfies Shape automaticallyio.Reader, io.Writer, fmt.Stringer). Define the interface in the package that uses it: accept interfaces, return concrete types.The empty interface
any (an alias of interface{}) has no methods, so every type satisfies it. You must recover the concrete type before using the value.
Type assertion and type switch
c, ok := s.(Circle) // ok is false if s does not hold a Circle
c2 := s.(Circle) // without ok: panics on mismatch
switch v := x.(type) {
case int:
fmt.Println("int", v)
case string:
fmt.Println("string", v)
default:
fmt.Println("other")
}The nil interface trap
func find() error {
var p *MyError = nil
return p // interface holding a nil pointer
}
fmt.Println(find() == nil) // false!nil only when both are nil. Return a literal nil for "no error", never a typed nil pointer.Method sets
If methods have pointer receivers, only *T satisfies the interface, not T. A method called through an interface is dispatched dynamically at run time.
Check yourself
- How does a Go type declare that it implements an interface?
- What does c, ok := s.(Circle) do when s does not hold a Circle?
- What is any in Go?
- A function returns a nil *MyError as type error. What does err == nil give?
- Type T has a method with a pointer receiver. Which type satisfies an interface requiring that method?
- Where should an interface usually be defined?
Go error handling in depth: wrapping, Is, As, panic and recover
Go errors form a chain: each layer wraps the error below with context, and errors.Is and errors.As search that chain.
Wrapping with %w
if err := loadUser(id); err != nil {
return fmt.Errorf("load user %d: %w", id, err)
}%w keeps the original error inside the new one. %v would only copy its text, and the chain would be lost.
Sentinel errors and errors.Is
var ErrNotFound = errors.New("not found")
if errors.Is(err, ErrNotFound) { ... } // true even when wrapped
if err == ErrNotFound { ... } // false once wrappedCustom error types and errors.As
type ValidationError struct{ Field string }
func (e *ValidationError) Error() string { return "invalid " + e.Field }
var ve *ValidationError
if errors.As(err, &ve) {
fmt.Println(ve.Field)
}errors.Is asks "is this specific error value in the chain?". errors.As asks "is there an error of this type in the chain?" and gives it to you.defer details
func f() {
x := 1
defer fmt.Println(x) // argument evaluated now: prints 1
x = 2
}Arguments of a deferred call are evaluated when the defer statement runs, not when the call happens.
panic and recover
func safe() (err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("recovered: %v", r)
}
}()
risky()
return nil
}recover works only inside a deferred function, and only for a panic in the same goroutine. An unrecovered panic in any goroutine crashes the whole program.Check yourself
- Which verb wraps an error so it stays in the chain?
- Which function tests whether a wrapped error chain contains a given sentinel error?
- What is errors.As used for?
- x := 1; defer fmt.Println(x); x = 2. What is printed when the function returns?
- Where must recover be called to stop a panic?
- An unrecovered panic in a background goroutine only stops that goroutine.
Goroutines, channels and select in Go
A goroutine is a lightweight thread managed by the Go runtime, started with the go keyword, and channels are typed pipes that goroutines use to communicate and synchronise.
Goroutines and WaitGroup
var wg sync.WaitGroup
for _, url := range urls {
wg.Add(1)
go func() {
defer wg.Done()
fetch(url)
}()
}
wg.Wait() // without this, main may exit before the goroutines finishWhen main returns, the program ends and all other goroutines are killed.
Channels
ch := make(chan int) // unbuffered
go func() { ch <- 42 }() // send
v := <-ch // receive
buf := make(chan int, 3) // buffered: capacity 3| Channel | Send blocks | Receive blocks |
|---|---|---|
| Unbuffered | Until a receiver is ready | Until a sender is ready |
| Buffered | Only when the buffer is full | Only when the buffer is empty |
Closing and ranging
go func() {
for i := 0; i < 3; i++ { ch <- i }
close(ch) // the sender closes
}()
for v := range ch { fmt.Println(v) } // ends when ch is closed
v, ok := <-ch // ok is false: closed and emptynil channel blocks forever.select
select {
case v := <-results:
fmt.Println(v)
case <-time.After(2 * time.Second):
fmt.Println("timeout")
}select waits on several channel operations and runs one that is ready. If several are ready, it picks one at random. A default case makes it non-blocking.
If every goroutine is blocked, the runtime stops with "all goroutines are asleep - deadlock!".
Check yourself
- How do you start a goroutine?
- When does a send on an unbuffered channel complete?
- What happens when you send on a closed channel?
- What does a receive from a closed, empty channel return?
- If several cases of a select are ready, which one runs?
- What is sync.WaitGroup used for?
Go sync, the race detector and context
When goroutines share memory, the sync package protects it, and the context package carries cancellation and deadlines across a chain of calls.
Data races and Mutex
type Counter struct {
mu sync.Mutex
n int
}
func (c *Counter) Inc() {
c.mu.Lock()
defer c.mu.Unlock()
c.n++
}A data race happens when two goroutines access the same variable at the same time and at least one writes. sync.RWMutex allows many readers or one writer. sync.Once runs initialisation exactly once. sync/atomic gives lock-free counters.
go vet reports this mistake.The race detector
go test -race ./... go run -race main.go
It finds races that actually occur during the run, so use it in tests and CI.
context
func fetch(ctx context.Context, url string) error {
req, _ := http.NewRequestWithContext(ctx, "GET", url, nil)
_, err := http.DefaultClient.Do(req)
return err
}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel() // always call cancel to release resources
err := fetch(ctx, url) // context.DeadlineExceeded after 2 s| Function | Purpose |
|---|---|
context.Background() | The root context |
WithCancel | Cancel by hand |
WithTimeout, WithDeadline | Cancel automatically after a time |
ctx.Done() | A channel closed on cancellation |
ctx.Err() | Why it was cancelled |
ctx context.Context as the first parameter of functions that do I/O or long work. Do not store it in a struct. Cancelling a parent cancels all contexts derived from it.select {
case <-ctx.Done():
return ctx.Err()
case job := <-jobs:
process(job)
}Check yourself
- What is a data race?
- Which flag enables Go's race detector?
- What does sync.RWMutex allow?
- By convention, where does context.Context go in a function signature?
- Why write defer cancel() after context.WithTimeout?
- Cancelling a parent context also cancels the contexts derived from it.
Go generics: type parameters and constraints
Generics, added in Go 1.18, let a function or type work with many types while staying fully type-checked at compile time.
Generic functions
func Map[T, U any](items []T, f func(T) U) []U {
out := make([]U, 0, len(items))
for _, it := range items {
out = append(out, f(it))
}
return out
}
lengths := Map([]string{"a", "bb"}, func(s string) int { return len(s) })Type arguments are usually inferred from the call.
Constraints
type Number interface {
~int | ~int64 | ~float64
}
func Sum[T Number](xs []T) T {
var total T
for _, x := range xs { total += x }
return total
}| Constraint | Allows |
|---|---|
any | Every type, but no operators |
comparable | Types usable with == and as map keys |
cmp.Ordered | Types usable with < and > |
~int | int and any type whose underlying type is int |
Generic types
type Stack[T any] struct{ items []T }
func (s *Stack[T]) Push(v T) { s.items = append(s.items, v) }
var s Stack[int]When to use generics
- Good: containers and helpers on slices, maps and channels (see the standard
slicesandmapspackages). - Not needed: when you only call methods on the value. Use an ordinary interface.
Check yourself
- In which Go version were generics introduced?
- Which constraint is required to use == on values of type T?
- What does ~int mean in a constraint?
- A method in Go can declare additional type parameters of its own.
- With the constraint any, which operation on T is allowed?
- When is an ordinary interface a better choice than a type parameter?
Go modules, packages and testing
A Go module is a versioned collection of packages described by a go.mod file, and testing is built into the toolchain with go test.
Modules
| File or command | Role |
|---|---|
go.mod | Module path, Go version, required dependencies and their versions |
go.sum | Checksums that verify downloaded dependencies |
go get pkg@v1.2.3 | Adds or upgrades a dependency |
go mod tidy | Adds missing and removes unused requirements |
Commit both go.mod and go.sum. A module at major version 2 or higher includes the version in its import path, for example example.com/lib/v2.
Packages
- One directory is one package.
- A directory named
internalcan be imported only by code inside the parent of that directory. - Import cycles are a compile error.
func init()runs automatically beforemain.
Table-driven tests
// file: math_test.go
func TestAdd(t *testing.T) {
tests := []struct {
name string
a, b, want int
}{
{"positive", 2, 3, 5},
{"negative", -1, -1, -2},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
if got := Add(tc.a, tc.b); got != tc.want {
t.Errorf("Add(%d, %d) = %d, want %d", tc.a, tc.b, got, tc.want)
}
})
}
}_test.go. Test functions are named TestXxx and take *testing.T. t.Errorf marks failure and continues; t.Fatalf stops the test.Benchmarks and useful flags
func BenchmarkAdd(b *testing.B) {
for i := 0; i < b.N; i++ { Add(2, 3) }
}go test ./... # all packages go test -run TestAdd -v # one test, verbose go test -cover # coverage go test -bench=. # benchmarks
Check yourself
- What is the purpose of go.sum?
- What must a Go test file name end with?
- Who can import a package placed under a directory named internal?
- What is the difference between t.Errorf and t.Fatalf?
- What does go mod tidy do?
- Go allows two packages to import each other.