Brainbotox · Lessons · Exams

Go Interview Questions, Advanced: Leaks, Scheduler, Escape Analysis (30 questions)

by lazizanie · Programming · Go · English

30 advanced Go (Golang) interview questions for senior developers with model answers: scheduler, garbage collector, channel and map internals, memory model, concurrency patterns, profiling and unsafe.

Take this exam on Brainbotox, with marking →

30 questions. The model answers are folded under each one.

Question 1

Q1. A leak behind a timeout. This function is called on every request with a context that times out after 100 ms. After a few hours in production the service's memory keeps growing.

func fetch(ctx context.Context) (string, error) {
    ch := make(chan string)
    go func() {
        ch <- slowCall()
    }()
    select {
    case s := <-ch:
        return s, nil
    case <-ctx.Done():
        return "", ctx.Err()
    }
}

(a) Explain the leak.

(b) Fix it.

(c) How would you find such a leak in a running service?

Model answer

(a) The leak. ch is unbuffered, so a send blocks until someone receives. When the context times out first, fetch returns and nobody will ever receive from ch. When slowCall finally returns, the goroutine blocks on ch <- for ever. Each timed-out request leaves one leaked goroutine, with its stack and the result it holds.

(b) Fix. Give the channel room for one value, so the send always succeeds, and pass the context down so the work itself stops.

func fetch(ctx context.Context) (string, error) {
    ch := make(chan string, 1) // buffered
    go func() {
        ch <- slowCall(ctx)   // honours cancellation
    }()
    select {
    case s := <-ch:
        return s, nil
    case <-ctx.Done():
        return "", ctx.Err()
    }
}

With the buffer, the goroutine sends, exits, and the channel is garbage collected. Passing ctx also stops wasting CPU and connections on work nobody wants.

(c) Finding it

  • Watch runtime.NumGoroutine() as a metric: a count that only climbs is the signal.
  • Take a goroutine profile with net/http/pprof (/debug/pprof/goroutine): thousands of goroutines parked on the same chan send line point straight at the bug.
  • In tests, use a leak detector such as goleak.

Revise: Advanced Go: Runtime, Memory, Concurrency Patterns, Performance

Question 2

Q2. The Go scheduler.

(a) Explain the three parts of the G-M-P model and how they relate.

(b) What happens when a goroutine makes a blocking system call?

(c) A goroutine runs a tight loop with no function calls. Can it block the other goroutines for ever?

Model answer

(a) G, M, P

  • G, a goroutine: the function to run, its small growable stack and its state.
  • M, a machine: an operating system thread that actually executes code.
  • P, a processor: a scheduling context with a local run queue. There are GOMAXPROCS of them, by default one per CPU core.

An M must hold a P to run Go code. So at most GOMAXPROCS goroutines run Go code in parallel, however many goroutines or threads exist. When a P's queue is empty, its M takes work from the global queue or steals half of another P's queue (work stealing).

(b) Blocking system call. The thread M is stuck in the kernel together with its goroutine. The runtime detaches the P from that M and hands it to another M (a parked one or a new one), so the other goroutines of that P keep running. When the call returns, the goroutine tries to get a P back, or else goes to the global queue.

Network I/O is different: it goes through the netpoller. The goroutine is parked and no thread is blocked, which is why one thread per connection is not needed.

(c) Tight loop. Not since Go 1.14. Earlier versions could only switch goroutines at function calls, so such a loop could starve others and even delay the garbage collector. Now a monitor thread (sysmon) notices a goroutine that has run for about 10 ms and sends its thread a signal: asynchronous preemption.

Revise: Advanced Go: Runtime, Memory, Concurrency Patterns, Performance

Question 3

Q3. Escape analysis.

type User struct{ Name string }
func NewUser(name string) *User {
    u := User{Name: name}
    return &u
}

(a) Is u allocated on the stack or on the heap, and who decides?

(b) How do you see the compiler's decision?

(c) Give two other common reasons a value escapes.

(d) A hot path allocates a 64 KB buffer per request. How does sync.Pool help, and what are its traps?

Model answer

(a) On the heap. The compiler decides, at build time, with escape analysis. The address of u is returned, so u must outlive the call and cannot live in the stack frame. In Go, returning the address of a local is safe: the compiler moves it to the heap. The syntax (new, &, a literal) does not decide; reachability does.

(b) See it:

go build -gcflags=-m ./...
# ./user.go:6:2: moved to heap: u

(c) Other causes of escape (any two):

  • Storing the value in an interface, for example passing it to fmt.Println.
  • Capturing it in a closure that outlives the function, or in a goroutine.
  • Sending a pointer to it on a channel, or storing the pointer in a heap object.
  • A slice whose size is not known at compile time, or is too large for the stack.

(d) sync.Pool. It keeps finished buffers and hands them to the next request, so the garbage collector has far fewer short-lived large objects to allocate and trace.

var bufPool = sync.Pool{
    New: func() any {
        b := make([]byte, 64<<10)
        return &b
    },
}
bp := bufPool.Get().(*[]byte)
defer bufPool.Put(bp)

Traps:

  • The pool is a cache, not a store: it may be emptied at any garbage collection.
  • A buffer comes back with old data in it: reset it before use.
  • Never use a buffer after Put.
  • Store pointers (*[]byte), or the slice header itself is allocated on every Put.
What a strong candidate adds: confirm with a benchmark and -benchmem before and after, since escaping is not a bug by itself.

Revise: Advanced Go: Runtime, Memory, Concurrency Patterns, Performance

Question 4

Q4. The garbage collector. Describe Go's garbage collector. What do GOGC and GOMEMLIMIT control?

Model answer

Go's collector is a concurrent, tri-color, mark and sweep collector. It is non-generational and non-moving.

  • Concurrent: marking runs at the same time as the program. There are only two very short stop-the-world pauses per cycle.
  • Tri-color: objects are white (not seen), grey (seen, children not yet scanned) or black (done). At the end, white objects are garbage.
  • A write barrier records pointer writes made during marking, so no live object is missed.
  • Non-moving: objects never change address, which keeps pointers and cgo simple, at the cost of some fragmentation.

Tuning:

  • GOGC (default 100): start a new cycle when the heap has grown by this percentage over the live heap after the last cycle. Higher means fewer collections and more memory.
  • GOMEMLIMIT: a soft limit on total memory. The collector works harder as the limit gets close. Useful in containers, to use the available memory without being killed.

The design goal is low latency, paid for with some CPU and throughput.

Question 5

Q5. Goroutine stacks. How can a program run a million goroutines when a million OS threads would be impossible? How do goroutine stacks grow?

Model answer
  • An OS thread reserves a large fixed stack, typically 1 to 8 MB, and switching threads goes through the kernel.
  • A goroutine starts with a very small stack, about 2 KB, managed by the Go runtime. A million of them is a couple of gigabytes, not terabytes.
  • Switching goroutines happens in user space and saves only a few registers.

Growth: each function prologue checks whether there is enough stack left. If not, the runtime allocates a new stack twice as large, copies the old one into it and adjusts the pointers that point into the stack. These are called contiguous (copying) stacks.

Consequences:

  • Deep recursion works, up to a maximum (1 GB by default on 64-bit), after which the program crashes with a stack overflow.
  • Stacks can shrink again during garbage collection.
  • Because stacks move, the address of a stack variable is not stable, which is one reason passing Go pointers to C is restricted.

Question 6

Q6. Channel internals. What is a channel made of inside the runtime? What happens, step by step, when a goroutine sends on an unbuffered channel that has a waiting receiver?

Model answer

A channel is a pointer to a runtime struct (hchan) that contains:

  • a mutex protecting the channel;
  • a circular buffer with its size and read and write positions (empty for unbuffered);
  • two wait queues: goroutines blocked on send, and goroutines blocked on receive;
  • a closed flag.

Send with a receiver already waiting:

  1. The sender locks the channel.
  2. It finds a goroutine in the receive queue.
  3. It copies the value directly into the receiver's memory, skipping the buffer.
  4. It marks the receiver runnable, so the scheduler will resume it.
  5. It unlocks and continues.

If no receiver is waiting and the buffer is full (or absent), the sender puts itself in the send queue and is parked: it gives up its thread, which runs another goroutine.

So channels are not lock-free. Under heavy contention a mutex-protected structure or atomics can be faster. Choose channels for clarity of ownership and signalling, not for raw speed.

Question 7

Q7. Mutex or channel. Go says: do not communicate by sharing memory, share memory by communicating. When do you still choose a sync.Mutex over a channel?

Model answer

Rule of thumb:

  • Channel when you are passing ownership of data, distributing work or signalling events: pipelines, worker pools, cancellation, results.
  • Mutex when you are protecting shared state: a cache, a counter, a map, the fields of a struct.

A mutex is the better tool when:

  • the critical section is a few lines that read or update a structure;
  • many goroutines need the same data, and none of them owns it;
  • performance matters: a mutex is cheaper than a channel operation.

Building a "state goroutine" with request and reply channels just to guard a map is more code, slower and easier to deadlock than:

mu.Lock()
m[key] = value
mu.Unlock()

Good practice with a mutex: keep it next to the fields it guards, keep the locked section short, never call unknown code or do I/O while holding it, and never copy a struct that contains one.

Question 8

Q8. Mutex behaviour. What are the two modes of sync.Mutex? What is special about how sync.RWMutex treats a waiting writer?

Model answer

sync.Mutex modes

  • Normal mode: waiting goroutines queue in order, but a goroutine that is woken up must compete with newly arriving goroutines that are already running on a CPU. The newcomers often win. This gives high throughput but is unfair.
  • Starvation mode: if a waiter fails to get the lock for more than 1 millisecond, the mutex switches mode. Now Unlock hands the lock directly to the first waiter, and new arrivals go to the back of the queue. When the queue is short again, it returns to normal mode.

This bounds the worst-case wait while keeping the fast path fast.

sync.RWMutex allows many readers or one writer. Once a writer is waiting, new readers are blocked until the writer has had its turn. Otherwise a steady stream of readers would starve writers.

Consequence: taking the read lock twice in the same goroutine (a recursive read lock) can deadlock if a writer arrives in between. Go mutexes are not reentrant.

Question 9

Q9. Atomics. When do you use sync/atomic and not a mutex? Write a thread-safe counter and explain compare-and-swap.

Model answer

Use atomics for a single value updated independently: counters, flags, a pointer to an immutable snapshot. They are lock-free and very fast. Use a mutex as soon as two or more values must change together.

var hits atomic.Int64
hits.Add(1)
n := hits.Load()

The typed values (atomic.Int64, atomic.Bool, atomic.Pointer[T], since Go 1.19) are preferred to the old functions, because the field cannot be read by accident without atomics.

Compare-and-swap sets a new value only if the current value is still the expected one, as one atomic step. It is the base of lock-free updates:

for {
    old := max.Load()
    if v <= old || max.CompareAndSwap(old, v) {
        break
    }
}   // retries if another goroutine changed max in between

Common pattern: a configuration snapshot behind atomic.Pointer[Config]. Readers call Load() with no lock. An update builds a new Config and calls Store(). The snapshot itself is never modified.

Question 10

Q10. The race detector. What is the difference between a data race and a race condition? What does go test -race find, and what can it not find?

Model answer
  • Data race: two goroutines access the same memory at the same time, at least one writes, and there is no synchronisation. In Go this is undefined behaviour, not just a wrong number.
  • Race condition: the result depends on timing or ordering. It can exist with no data race at all, for example a check and an update each done under a lock, but as two separate locked steps.

-race instruments memory accesses and reports data races that actually happen during the run, with the stacks of both accesses.

Limits:

  • It only sees code paths that are executed. A race in an untested path is not reported. No report does not mean no race.
  • It does not find race conditions that involve no unsynchronised memory access, nor deadlocks.
  • It costs roughly 5 to 10 times more memory and 2 to 20 times more CPU, so it is used in tests and CI, and sometimes on one production instance, not everywhere.

It reports no false positives: every report is a real race.

Question 11

Q11. The memory model. Can this program print nothing and loop for ever? Why, and how do you fix it?

var done bool
func main() {
    go func() {
        time.Sleep(time.Second)
        done = true
    }()
    for !done {
    }
    fmt.Println("finished")
}
Model answer

Yes. done is written by one goroutine and read by another with no synchronisation: a data race.

The Go memory model only guarantees that a read sees a write when there is a happens-before relationship between them, created by a channel operation, a mutex, sync.WaitGroup, sync/atomic and so on. Here there is none, so the compiler may assume done does not change inside the loop, read it once, and turn the loop into for {}.

Fix with a channel, which also removes the busy loop that burns a CPU:

done := make(chan struct{})
go func() {
    time.Sleep(time.Second)
    close(done)
}()
<-done
fmt.Println("finished")

Or with atomic.Bool if polling is really wanted.

Lesson: "it works on my machine" proves nothing about a data race. Correctness comes from the memory model, not from observed behaviour.

Question 12

Q12. errgroup. You must fetch 3 resources concurrently, return the first error, and stop the other requests as soon as one fails. Write it.

Model answer
import "golang.org/x/sync/errgroup"
func loadAll(ctx context.Context) (*Page, error) {
    g, ctx := errgroup.WithContext(ctx)
    var (
        user   *User
        orders []Order
        prefs  *Prefs
    )
    g.Go(func() (err error) {
        user, err = fetchUser(ctx)
        return err
    })
    g.Go(func() (err error) {
        orders, err = fetchOrders(ctx)
        return err
    })
    g.Go(func() (err error) {
        prefs, err = fetchPrefs(ctx)
        return err
    })
    if err := g.Wait(); err != nil {
        return nil, err
    }
    return &Page{user, orders, prefs}, nil
}
  • errgroup.WithContext returns a context that is cancelled as soon as one function returns an error, so the others stop if they honour ctx.
  • g.Wait() waits for all of them and returns the first error.
  • Each goroutine writes its own variable, and they are read only after Wait, so there is no race.
  • g.SetLimit(n) bounds the number of goroutines running at once.

It replaces a hand-written WaitGroup, error channel and sync.Once.

Question 13

Q13. Pipelines. Explain fan-out and fan-in. What must every stage of a pipeline do so that no goroutine leaks when the consumer stops early?

Model answer
  • A pipeline is a chain of stages connected by channels. Each stage receives values, does work, and sends results on.
  • Fan-out: several goroutines read from the same channel to share the work of a slow stage.
  • Fan-in: several channels are merged into one.

The leak: if the consumer stops reading, upstream stages block for ever on their send. So every send must also watch for cancellation.

func square(ctx context.Context, in <-chan int) <-chan int {
    out := make(chan int)
    go func() {
        defer close(out)              // always close what you own
        for n := range in {
            select {
            case out <- n * n:
            case <-ctx.Done():        // consumer left: stop
                return
            }
        }
    }()
    return out
}

Rules for each stage:

  1. Close its output channel when it is done (with defer).
  2. Stop when its input is closed.
  3. Stop when the context is cancelled, on receive and on send.

The caller cancels the context with defer cancel(), which unblocks every stage on any exit path.

Question 14

Q14. Limiting concurrency and rate. Show two different controls: (a) at most 10 goroutines working at once, (b) at most 50 requests per second.

Model answer

(a) Concurrency limit: a buffered channel used as a semaphore.

sem := make(chan struct{}, 10)
var wg sync.WaitGroup
for _, u := range urls {
    wg.Add(1)
    sem <- struct{}{}          // blocks when 10 are running
    go func() {
        defer wg.Done()
        defer func() { <-sem }()
        fetch(u)
    }()
}
wg.Wait()

The acquire happens before starting the goroutine, so the loop itself is slowed down and goroutines do not pile up.

(b) Rate limit: a token bucket.

import "golang.org/x/time/rate"
lim := rate.NewLimiter(rate.Limit(50), 10) // 50 per second, burst 10
for _, u := range urls {
    if err := lim.Wait(ctx); err != nil {
        return err
    }
    go fetch(u)
}

They answer different questions: how many at once protects your own resources (memory, connections), and how many per second protects the service you call. Real clients often need both.

Question 15

Q15. Context pitfalls. List four mistakes people make with context.Context, and say what context.Value should and should not be used for.

Model answer
  1. Not calling cancel. Every WithCancel, WithTimeout and WithDeadline must have its cancel called, usually with defer, or its resources live until the parent ends.
  2. Storing a context in a struct. A context belongs to one call. Pass it as the first parameter.
  3. Using the request context for background work. When the handler returns, the context is cancelled and the work is killed. Use a separate context, or context.WithoutCancel(ctx) (Go 1.21) to keep the values and drop the cancellation.
  4. Ignoring it. Accepting ctx but never checking ctx.Done() or passing it down. Cancellation only works if every blocking call observes it.
  5. Passing nil. Use context.TODO() when you do not have one yet.

context.Value is for request-scoped data that crosses API boundaries: a trace id, the authenticated user, a logger. It is not for optional parameters or dependencies such as a database handle: those are untyped, invisible in the signature, and fail at run time.

Use a private key type to avoid collisions: type ctxKey struct{}.

Question 16

Q16. Timers in a loop. What is the problem with this loop on a busy channel, and how do you write it properly?

for {
    select {
    case m := <-msgs:
        handle(m)
    case <-time.After(time.Minute):
        log.Println("idle")
    }
}
Model answer

time.After creates a new timer on every iteration. When a message arrives first, that timer is abandoned.

  • Before Go 1.23, an abandoned timer was not collected until it fired. With thousands of messages per second and a one minute timeout, hundreds of thousands of live timers pile up: a memory and CPU problem.
  • Since Go 1.23, unreferenced timers can be garbage collected, so it is no longer a leak, but allocating a timer per message is still wasteful.

Reuse one timer:

idle := time.NewTimer(time.Minute)
defer idle.Stop()
for {
    select {
    case m := <-msgs:
        handle(m)
        idle.Reset(time.Minute)
    case <-idle.C:
        log.Println("idle")
        idle.Reset(time.Minute)
    }
}

Before Go 1.23, Reset on a timer that might already have fired required stopping it and draining its channel first. Go 1.23 made Reset and Stop safe without that. For a fixed interval, use time.NewTicker and stop it with defer t.Stop().

Question 17

Q17. Interface internals. How is an interface value represented in memory? What are the costs of calling a method through an interface?

Model answer

An interface value is two words:

  • a pointer to type information: for a non-empty interface an itab, which holds the dynamic type and a table of function pointers for the interface's methods; for any, just the type;
  • a pointer to the data.

This explains the nil trap: an interface is nil only when both words are nil.

Costs:

  • Indirect call: the method address is read from the itab at run time. The call usually cannot be inlined, which also blocks further optimisations.
  • Allocation: putting a value that is not a pointer into an interface generally copies it to the heap, so the data word can point to it. Small values and constants are optimised in some cases.
  • Escape: the compiler often cannot prove what the callee does with the value, so arguments passed as interfaces tend to escape to the heap.

The compiler can sometimes devirtualise a call when it knows the concrete type, and profile-guided optimisation (PGO) does it for hot call sites.

In normal code this cost is negligible. It matters in tight loops, where a concrete type or a generic function avoids it.

Question 18

Q18. Slices that keep memory alive. This function reads a 500 MB file and returns its first 100 bytes. Why does the program keep 500 MB in use, and how do you fix it?

func header(path string) ([]byte, error) {
    data, err := os.ReadFile(path)
    if err != nil {
        return nil, err
    }
    return data[:100], nil
}
Model answer

data[:100] is a slice header that still points into the same 500 MB array. The garbage collector works on whole allocations: as long as any slice refers to that array, the entire array stays alive, even though only 100 bytes are reachable through it.

Fix: copy the bytes you need into a new, small array.

return bytes.Clone(data[:100]), nil
// or: append([]byte(nil), data[:100]...)

Better still, do not read the whole file:

f, err := os.Open(path)
if err != nil {
    return nil, err
}
defer f.Close()
buf := make([]byte, 100)
_, err = io.ReadFull(f, buf)
return buf, err

The same thing happens with strings (a small substring keeps a huge string alive: use strings.Clone) and with slices of pointers: removing an element by reslicing leaves the pointer in the hidden part of the array, so set it to nil first or use slices.Delete, which clears it.

Question 19

Q19. Map internals. How does a Go map work inside? Why is iteration order random, why can you not take the address of a map element, and does a map shrink after deleting keys?

Model answer

A map is a hash table. The key is hashed with a per-map random seed. Part of the hash selects a group of slots, and a few more bits are stored as a small tag per slot so most non-matching keys are rejected without a full comparison.

  • The classic implementation used buckets of 8 entries with overflow buckets. Since Go 1.24 the runtime uses a design based on Swiss tables, which is faster and more compact.
  • When the table is too full it grows. Growth is done incrementally, spread over later operations, to avoid one long pause.

Consequences:

  • Random iteration order: the runtime deliberately starts each iteration at a random position, so nobody depends on an order that would change with growth anyway.
  • No &m[k]: growth moves entries, so an address would become invalid. To modify a struct value, copy it out, change it and store it back, or store pointers.
  • No shrinking: deleting keys frees the slots for reuse, but the table's memory is not returned. A map that was once huge stays large. Build a new map to reclaim it.
  • Not safe for concurrent writes.

Question 20

Q20. Struct layout. On a 64-bit machine, what are the sizes of these two structs, and why? What is false sharing?

type A struct {
    a bool
    b int64
    c bool
}
type B struct {
    b int64
    a bool
    c bool
}
Model answer

A is 24 bytes, B is 16 bytes.

Each field must sit at an address that is a multiple of its alignment, and an int64 needs a multiple of 8. The compiler keeps fields in the declared order and inserts padding.

  • A: a (1 byte) + 7 padding + b (8) + c (1) + 7 padding at the end = 24.
  • B: b (8) + a (1) + c (1) + 6 padding = 16.

Ordering fields from largest to smallest removes most padding. It matters when you hold millions of values: fewer bytes and more values per cache line. Check with unsafe.Sizeof, or the fieldalignment analyser.

False sharing: two goroutines on different cores write to different variables that happen to share one CPU cache line (usually 64 bytes). Each write invalidates the line in the other core's cache, so they slow each other down although they share no data. Fix by padding the hot fields apart so each has its own cache line.

Question 21

Q21. Compiler optimisations. What are inlining and bounds check elimination? How do you see what the compiler decided?

Model answer

Inlining replaces a call to a small function with the function's body. It removes the call overhead and, more importantly, lets the compiler optimise across the call: escape analysis and constant folding see through it.

  • The compiler inlines functions below a complexity budget. Since Go 1.20, profile-guided optimisation (PGO) inlines hot functions beyond that budget.
  • Calls through interfaces or function values usually cannot be inlined.

Bounds check elimination (BCE): every s[i] is checked against len(s). The compiler removes the check when it can prove the index is in range.

func sum4(s []int) int {
    _ = s[3]            // one check here...
    return s[0] + s[1] + s[2] + s[3]   // ...none here
}

A for i := range s loop needs no checks on s[i].

See the decisions:

go build -gcflags='-m'                    # inlining, escapes
go build -gcflags='-d=ssa/check_bce/debug=1'   # remaining checks

Use these on a hot path that a profile has identified. Elsewhere, write clear code.

Question 22

Q22. Profiling. A Go service is slow and uses too much memory. Which tools do you use, and what does each profile type tell you?

Model answer

Start by measuring. Expose net/http/pprof (on an internal port) and read profiles with go tool pprof.

  • CPU profile: where CPU time is spent, by sampling running stacks. Shows hot functions.
  • Heap profile: inuse_space shows what is holding memory now (leaks, large caches). alloc_space shows what allocates the most over time (GC pressure).
  • Goroutine profile: all goroutine stacks. Finds leaks and where goroutines are stuck.
  • Block profile: time spent blocked on channels and locks.
  • Mutex profile: which locks are contended.
  • Execution trace (go tool trace): a timeline of scheduling, GC and blocking. Good for latency problems that a CPU profile does not explain.
go tool pprof http://host:6060/debug/pprof/profile?seconds=30
go tool pprof -http=:8080 heap.pprof     # flame graph

For a specific function, write a benchmark and compare runs properly:

go test -bench=. -benchmem -count=10 > new.txt
benchstat old.txt new.txt

Order of work: measure, change one thing, measure again. Most gains come from fewer allocations and better algorithms, not micro-tuning.

Question 23

Q23. How generics are compiled. How does Go implement generics, and what does that mean for performance compared with a hand-written function or an interface?

Model answer

Go uses GC shape stenciling with dictionaries, a middle path between two extremes.

  • Full monomorphisation (C++, Rust) would generate one copy of the function per type argument: fastest code, larger binaries, slower builds.
  • Go generates one copy per GC shape: types with the same underlying memory layout share an instantiation. In particular, all pointer types share one shape.
  • A hidden dictionary argument carries the type-specific information the shared code needs, such as method tables.

Consequences:

  • For value types such as int or float64, generic code is specialised and is about as fast as hand-written code.
  • For pointer types, calling a method on a type parameter goes through the dictionary. It can be as slow as, or slower than, an interface call, and is not inlined.
  • Generics do not automatically beat interfaces. They remove boxing and give type safety. Measure before using them for speed.

Good uses: containers and algorithms (slices, maps, a generic cache). For behaviour that varies by type, an interface remains the natural tool.

Question 24

Q24. unsafe. What is unsafe.Pointer for? Why is this code a bug?

addr := uintptr(unsafe.Pointer(&x))
runtime.GC()
p := (*int)(unsafe.Pointer(addr))
Model answer

unsafe.Pointer can be converted to and from any pointer type and to uintptr. It bypasses the type system, for a few low-level jobs: system calls, reading memory laid out by C, zero-copy conversions, and the internals of sync/atomic and reflect.

The bug: a uintptr is just an integer. The garbage collector does not treat it as a reference.

  • Once addr is the only thing that knows where x is, the collector may free x.
  • If x lived on a stack that is then moved, the integer is not updated.

Turning the integer back into a pointer gives a pointer to memory that may no longer hold x.

The rule: conversion to uintptr, arithmetic and conversion back must happen in one expression, with no uintptr stored in a variable.

p := (*T)(unsafe.Add(unsafe.Pointer(&s), unsafe.Offsetof(s.f)))

unsafe.Add, unsafe.Slice and unsafe.String exist to do the common cases correctly. Code that imports unsafe is not covered by the Go compatibility promise. Run go vet, and test with -gcflags=-d=checkptr.

Question 25

Q25. cgo. What are the costs and risks of calling C from Go with cgo? When is it worth it?

Model answer

Costs

  • Each call is expensive: tens of nanoseconds, against about one for a Go call. The goroutine must switch from its small Go stack to a system stack, and the scheduler is informed.
  • A C call that blocks holds an OS thread. Many concurrent blocking calls create many threads, losing the benefit of goroutines.
  • The Go scheduler, garbage collector, race detector and profiler cannot see inside C code.
  • Build: a C toolchain is required, cross-compilation becomes hard, builds are slower, and a fully static binary is harder to produce.

Risks

  • Memory safety is gone: a bug in C corrupts the Go heap.
  • Pointer rules: C may not keep a Go pointer after the call returns, and Go memory passed to C must not itself contain Go pointers (unless pinned with runtime.Pinner). The collector does not know what C holds.
  • Memory allocated by C (C.CString, C.malloc) must be freed by hand with C.free.

Worth it when a mature C library has no good Go equivalent (a database engine, a codec, a GPU library) and the calls are coarse: do a lot of work per call, not many tiny calls in a loop.

Question 26

Q26. Reflection. What does this print, and why? Then say when reflection is appropriate in Go.

x := 3.4
v := reflect.ValueOf(x)
fmt.Println(v.CanSet())
p := reflect.ValueOf(&x).Elem()
fmt.Println(p.CanSet())
p.SetFloat(7.1)
fmt.Println(x)
Model answer

It prints false, true, 7.1.

  • reflect.ValueOf(x) receives a copy of x. Setting it would change the copy, which is useless, so the value is not settable. Calling SetFloat on it would panic.
  • reflect.ValueOf(&x).Elem() starts from a pointer and follows it. That value refers to the real x, so it is addressable and settable.

This is the third "law of reflection": to modify a value through reflection, you must pass a pointer. It is why json.Unmarshal(data, &v) needs &v. Unexported struct fields are never settable.

Appropriate uses: code that must work with types it cannot know in advance: encoders and decoders, ORMs, dependency injection, validation driven by struct tags, test helpers such as deep comparison.

Costs: much slower than direct code, allocations, and errors that move from compile time to run time as panics. Prefer generics or interfaces when the set of types is known, and code generation when performance matters.

Question 27

Q27. Graceful shutdown. Write the main of an HTTP server that, on SIGTERM, stops accepting new connections and lets requests in progress finish, for at most 10 seconds.

Model answer
func main() {
    ctx, stop := signal.NotifyContext(context.Background(),
        syscall.SIGINT, syscall.SIGTERM)
    defer stop()
    srv := &http.Server{Addr: ":8080", Handler: newRouter()}
    go func() {
        err := srv.ListenAndServe()
        if err != nil && !errors.Is(err, http.ErrServerClosed) {
            log.Fatalf("listen: %v", err)
        }
    }()
    <-ctx.Done()            // wait for the signal
    shutdownCtx, cancel := context.WithTimeout(
        context.Background(), 10*time.Second)
    defer cancel()
    if err := srv.Shutdown(shutdownCtx); err != nil {
        log.Printf("forced shutdown: %v", err)
    }
}
  • signal.NotifyContext gives a context that is cancelled when the signal arrives.
  • srv.Shutdown closes the listeners, then waits for active requests to finish, until its context expires.
  • ListenAndServe returns http.ErrServerClosed after a shutdown: that is not an error.
  • The shutdown context is new. The first one is already cancelled.

Also needed in practice: stop background workers and close the database after the server, and in Kubernetes fail the readiness probe first so the load balancer stops sending traffic.

Question 28

Q28. HTTP client pitfalls. Find the three problems in this function, which is called thousands of times per minute.

func status(url string) (int, error) {
    client := &http.Client{}
    resp, err := client.Get(url)
    if err != nil {
        return 0, err
    }
    return resp.StatusCode, nil
}
Model answer
  1. No timeout. The zero value of http.Client waits for ever. One server that accepts the connection and never answers blocks the goroutine permanently. Set Timeout, and pass a context.
  2. The body is never closed. The caller must always close resp.Body. Otherwise the connection, its file descriptor and a goroutine are leaked on every call.
  3. A new client on every call. A new client means a new Transport and a new connection pool, so no connection is ever reused: a TCP and TLS handshake each time. Create one client and share it. It is safe for concurrent use.
var client = &http.Client{Timeout: 10 * time.Second}
func status(ctx context.Context, url string) (int, error) {
    req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
    if err != nil {
        return 0, err
    }
    resp, err := client.Do(req)
    if err != nil {
        return 0, err
    }
    defer resp.Body.Close()
    io.Copy(io.Discard, resp.Body)   // drain so the connection is reused
    return resp.StatusCode, nil
}

Draining the body matters: a connection whose body was not read to the end cannot go back to the pool.

Question 29

Q29. Initialisation order. In what order does Go initialise packages, package-level variables and init functions? Why should init be used sparingly?

Model answer

Order:

  1. Imported packages first, recursively. Each package is initialised exactly once, after all the packages it imports.
  2. Inside a package, package-level variables are initialised in dependency order: a variable that depends on another is initialised after it, whatever the order in the source.
  3. Then the package's init() functions run. A file may have several, and they run in the order they appear. Across files, the order is the order the files are given to the compiler, in practice alphabetical by file name.
  4. Finally main.main() starts.

All of this runs in a single goroutine.

Why use init sparingly:

  • It runs as a side effect of an import, invisibly. Importing a package for one function also runs its init.
  • It cannot return an error, so failures become panics or log.Fatal at start-up.
  • It usually sets global state, which makes code hard to test and couples packages.
  • It adds to start-up time for every program that imports the package.

Prefer an explicit constructor called from main. Acceptable uses: registering a driver or codec (the import _ "pkg" pattern) and precomputing a constant table.

Question 30

Q30. Strings and byte slices. What does converting between string and []byte cost? How do you build a large string efficiently, and how do you avoid the conversion cost when it matters?

Model answer

Strings are immutable and byte slices are mutable. So []byte(s) and string(b) must allocate and copy, otherwise changing the slice would change the string.

The compiler removes the copy in a few safe cases:

  • a map lookup m[string(b)];
  • a comparison string(b) == "x";
  • for range []byte(s).

Building a string: s += x in a loop copies everything each time, which is quadratic. Use strings.Builder:

var sb strings.Builder
sb.Grow(size)                 // optional: one allocation
for _, p := range parts {
    sb.WriteString(p)
}
s := sb.String()              // no copy

Avoiding conversions:

  • stay in one representation: the bytes package mirrors strings;
  • write with io.WriteString(w, s) or fmt.Fprintf instead of w.Write([]byte(s));
  • append into a reused buffer with strconv.AppendInt, fmt.Appendf.

Last resort, after profiling: unsafe.String(unsafe.SliceData(b), len(b)) gives a string that shares the bytes with no copy. It is only correct if the bytes are never modified afterwards.