Brainbotox · Lessons · Exams

Go Intermediate for Confirmed Developers: Interfaces, Goroutines

by lazizanie · Programming · Go · English

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 automatically
Keep interfaces small, often one method (io.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!
An interface value holds a (type, value) pair. It equals 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

  1. How does a Go type declare that it implements an interface?
  2. What does c, ok := s.(Circle) do when s does not hold a Circle?
  3. What is any in Go?
  4. A function returns a nil *MyError as type error. What does err == nil give?
  5. Type T has a method with a pointer receiver. Which type satisfies an interface requiring that method?
  6. Where should an interface usually be defined?

Take the quiz on Brainbotox

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 wrapped

Custom 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

  1. Which verb wraps an error so it stays in the chain?
  2. Which function tests whether a wrapped error chain contains a given sentinel error?
  3. What is errors.As used for?
  4. x := 1; defer fmt.Println(x); x = 2. What is printed when the function returns?
  5. Where must recover be called to stop a panic?
  6. An unrecovered panic in a background goroutine only stops that goroutine.

Take the quiz on Brainbotox

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 finish

When 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
ChannelSend blocksReceive blocks
UnbufferedUntil a receiver is readyUntil a sender is ready
BufferedOnly when the buffer is fullOnly 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 empty
Sending on a closed channel panics. Closing a channel twice panics. A send or receive on a nil 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.

Go's motto: do not communicate by sharing memory; share memory by communicating.

If every goroutine is blocked, the runtime stops with "all goroutines are asleep - deadlock!".

Check yourself

  1. How do you start a goroutine?
  2. When does a send on an unbuffered channel complete?
  3. What happens when you send on a closed channel?
  4. What does a receive from a closed, empty channel return?
  5. If several cases of a select are ready, which one runs?
  6. What is sync.WaitGroup used for?

Take the quiz on Brainbotox

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.

Never copy a struct that contains a mutex. Pass it by pointer. 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
FunctionPurpose
context.Background()The root context
WithCancelCancel by hand
WithTimeout, WithDeadlineCancel automatically after a time
ctx.Done()A channel closed on cancellation
ctx.Err()Why it was cancelled
Pass 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

  1. What is a data race?
  2. Which flag enables Go's race detector?
  3. What does sync.RWMutex allow?
  4. By convention, where does context.Context go in a function signature?
  5. Why write defer cancel() after context.WithTimeout?
  6. Cancelling a parent context also cancels the contexts derived from it.

Take the quiz on Brainbotox

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
}
ConstraintAllows
anyEvery type, but no operators
comparableTypes usable with == and as map keys
cmp.OrderedTypes usable with < and >
~intint 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]
A method cannot declare its own type parameters. Only the type and top-level functions can.

When to use generics

  • Good: containers and helpers on slices, maps and channels (see the standard slices and maps packages).
  • Not needed: when you only call methods on the value. Use an ordinary interface.
Start with concrete code. Introduce a type parameter when you find yourself writing the same function for a second type.

Check yourself

  1. In which Go version were generics introduced?
  2. Which constraint is required to use == on values of type T?
  3. What does ~int mean in a constraint?
  4. A method in Go can declare additional type parameters of its own.
  5. With the constraint any, which operation on T is allowed?
  6. When is an ordinary interface a better choice than a type parameter?

Take the quiz on Brainbotox

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 commandRole
go.modModule path, Go version, required dependencies and their versions
go.sumChecksums that verify downloaded dependencies
go get pkg@v1.2.3Adds or upgrades a dependency
go mod tidyAdds 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 internal can be imported only by code inside the parent of that directory.
  • Import cycles are a compile error.
  • func init() runs automatically before main.

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 files end in _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

  1. What is the purpose of go.sum?
  2. What must a Go test file name end with?
  3. Who can import a package placed under a directory named internal?
  4. What is the difference between t.Errorf and t.Fatalf?
  5. What does go mod tidy do?
  6. Go allows two packages to import each other.

Take the quiz on Brainbotox