Go Interview Questions
Go interviews test a short list of ideas, and they test them hard. The language is small enough that an interviewer can't hide behind trivia, so the questions go after mechanics instead: what a slice really is, why a nil pointer can make an interface non-nil, what -race can and can't see, who should close a channel. This page collects the questions that come up again and again, answers them from first principles, and backs every claim with a program you can run.
The Go Cheat Sheet is the syntax reference and Go Concurrency is the long-form guide to the scheduler, channels and patterns. This page doesn't repeat them. It asks the questions those pages prepare you for.
How to use this page
Questions are grouped by the level at which they are usually asked, and by topic inside each level:
| Part | Level | Topics |
|---|---|---|
| Part 1 | Junior | Zero values, arrays and slices, maps, strings and runes, structs, methods, interfaces, defer, errors, closures, first goroutines and channels |
| Part 2 | Senior | Typed nil, generics, iterators, error design, panic across goroutines, init order, the scheduler, select, context, the sync package, leaks, the race detector, testing |
| Part 3 | Staff | The memory model, escape analysis, the GC and its knobs, profiling, allocation control, modules and tooling, API design |
| Part 4 | All levels | Worker pool, rate limiter, pub-sub, retry with backoff, LRU cache, singleflight, pipeline — each with tests |
| Part 5 | All levels | "What does this print?" puzzles with explanations |
Every question has the same shape: the answer, a runnable example, the common wrong answer, and the follow-up an interviewer asks next. Every program on this page was run with Go 1.26.1 (concurrent code with go run -race or go test -race). Save a snippet as main.go next to a go.mod that says go 1.26, then go run .. Where the output depends on scheduling or randomness the text says "may print".
What interviewers are actually grading
At junior level: can you predict what the code does? At senior level: can you explain why in terms of the runtime's real structures (the slice header, the interface's type word, the channel's wait queues)? At staff level: can you reason about trade-offs (allocation, contention, API stability, failure modes) and say what you would ship?
Part 1: Junior
Values, Types and Zero Values
Q: What is a zero value, and why does Go have them?
Every variable in Go is initialized. If you don't give it a value, it gets the zero value for its type: 0 for numbers, false for booleans, "" for strings, and nil for pointers, slices, maps, channels, functions and interfaces. A struct's zero value is a struct whose fields are all zero values, recursively. There is no "uninitialized memory" state to read by mistake, which removes a whole class of C bugs.
The design goal the Go authors call "make the zero value useful" goes further: well-designed types work without a constructor. A sync.Mutex is unlocked, a bytes.Buffer is empty and ready for writes, a nil slice can be appended to and ranged over.
package main
import (
"bytes"
"fmt"
"sync"
)
type Config struct {
Name string
Retries int
Verbose bool
Tags []string
Limits map[string]int
Next *Config
}
func main() {
var c Config
fmt.Printf("%q %d %t %t %t %t\n", c.Name, c.Retries, c.Verbose,
c.Tags == nil, c.Limits == nil, c.Next == nil)
var mu sync.Mutex // usable as is: unlocked
mu.Lock()
mu.Unlock()
var buf bytes.Buffer // usable as is: empty
buf.WriteString("hi")
c.Tags = append(c.Tags, "a") // appending to a nil slice works
fmt.Println(buf.String(), c.Tags, c.Limits["missing"]) // reading a nil map works
}
Output:
"" 0 false true true true
hi [a] 0
The one zero value that is a trap is the nil map: reads work, writes panic (see the maps question below).
Common wrong answer: "Uninitialized variables are nil." Only reference-like types are nil. An int is 0 and a struct is never nil; only a pointer to a struct can be.
Follow-up: How do you tell "not set" from "set to zero" in a config struct? Use a pointer field (*int, where nil means not set), a separate bool flag, or a wrapper type. Go 1.26 made the pointer route less clunky: new now accepts an expression, so Retries: new(3) gives you a *int pointing at 3 without a helper function.
Arrays and Slices
Q: What is the difference between an array and a slice? What is a slice header?
An array is a fixed-length value: [4]int is a type, its length is part of that type, and assigning or passing it copies every element. A slice is a small descriptor, the slice header, that points into an array someone else owns. The header has three words: a pointer to the first element, the length (how many elements you can index) and the capacity (how many elements exist from the pointer to the end of the backing array).
flowchart LR
S["s := arr[1:3]<br/>ptr | len=2 | cap=4"] -->|"ptr"| A1
subgraph backing["arr: [5]int"]
A0["0"] --- A1["1"] --- A2["2"] --- A3["3"] --- A4["4"]
end
Because the header is copied by value but the array is shared, passing a slice to a function is cheap (24 bytes on a 64-bit machine) and lets the callee modify elements the caller sees.
package main
import (
"fmt"
"unsafe"
)
func main() {
arr := [5]int{0, 1, 2, 3, 4}
cp := arr // arrays are values: this copies all five ints
cp[0] = 99
fmt.Println(arr[0], cp[0])
s := arr[1:3] // a view onto arr
fmt.Println(s, len(s), cap(s))
s[0] = 42 // writes through to arr
fmt.Println(arr)
fmt.Println(unsafe.Sizeof(s)) // pointer + len + cap
}
Output:
0 99
[1 2] 2 4
[0 42 2 3 4]
24
Common wrong answer: "Slices are passed by reference." Go passes everything by value. The slice header is copied; it just happens to contain a pointer. That is why a callee can change s[0] for the caller but cannot change the caller's len(s) by appending.
Follow-up: When would you use an array? For fixed-size values that should be compared or used as map keys ([32]byte hashes, [2]int grid coordinates), and when you want copy semantics.
Q: How does append grow a slice?
If len < cap, append writes into the spare capacity and returns a header with a bigger length; no allocation. If the slice is full, append allocates a new, larger array, copies the old elements, and returns a header pointing at the new array. That is why you must always use the result: s = append(s, x).
The growth policy lives in the runtime (nextslicecap in runtime/slice.go). In current versions it doubles the capacity for small slices, then, past 256 elements, it moves smoothly towards growing by about 1.25×, and finally rounds the byte size up to the allocator's size class. The numbers are an implementation detail, not a promise.
package main
import "fmt"
func main() {
var s []int
last := -1
for i := 0; i < 2000; i++ {
s = append(s, i)
if cap(s) != last {
fmt.Print(cap(s), " ")
last = cap(s)
}
}
fmt.Println()
}
On Go 1.26.1 (amd64) this printed:
4 8 16 32 64 128 256 512 848 1280 1792 2560
Notice the first capacity is 4, not 1. Recent compilers can give a small non-escaping slice a 32-byte backing store on the stack, and four ints fit in it. And 848 instead of 832 is the size-class rounding at work.
If you know the final size, preallocate: make([]int, 0, n) does one allocation instead of about a dozen.
Common wrong answer: "append always doubles." It doubles only while the slice is small, and the result is rounded to size classes.
Follow-up: What does append(s, other...) do when other is much bigger than cap(s)? If the needed length is more than double the old capacity, the runtime sizes the new array to the needed length (then rounds up), skipping the doubling steps.
Q: Explain the slice aliasing trap.
Two slices that share a backing array see each other's writes, and append on a slice with spare capacity writes into that shared array. The classic bug is calling append twice on the same base slice and expecting two independent results:
package main
import "fmt"
func main() {
base := make([]int, 3, 10) // len 3, cap 10: spare room after index 2
a := append(base, 1) // writes index 3 of the shared array
b := append(base, 2) // writes index 3 again
fmt.Println(a[3], b[3])
// The same bug, in a function that "just adds a default"
withDefault := func(xs []int) []int { return append(xs, -1) }
nums := []int{1, 2, 3, 4}
head := nums[:2]
_ = withDefault(head)
fmt.Println(nums) // nums[2] was overwritten
// Fix: cap the slice so append must copy
safe := nums[:2:2]
_ = withDefault(safe)
fmt.Println(nums)
}
Output:
2 2
[1 2 -1 4]
[1 2 -1 4]
The last line is unchanged from the line before: the full slice expression nums[:2:2] set capacity to 2, so append had to allocate a new array and nums was left alone.
A related trap is holding onto a small sub-slice of a huge array: header := data[:16] keeps all of data alive for the garbage collector. Copy what you need (slices.Clone(data[:16])) if data is large.
Common wrong answer: "a and b are different variables, so they are independent." The variables are different headers pointing at the same array.
Follow-up: How do you write a function that returns a modified slice without surprising the caller? Either document that it may reuse the input (like append itself), or clone first with slices.Clone and work on the copy.
Q: What do copy and the full slice expression s[low:high:max] do?
copy(dst, src) copies min(len(dst), len(src)) elements and returns that number. It handles overlapping slices correctly (it behaves like memmove), and it is the standard way to make an independent copy. It never grows dst, so copying into a nil or zero-length slice copies nothing.
The three-index slice s[low:high:max] creates a slice with length high-low and capacity max-low. Its job is to limit capacity, so that a later append cannot overwrite elements beyond high that someone else owns.
package main
import (
"fmt"
"slices"
)
func main() {
src := []int{1, 2, 3, 4, 5}
var empty []int
fmt.Println(copy(empty, src)) // 0: dst has no length
dst := make([]int, 3)
n := copy(dst, src)
fmt.Println(n, dst)
copy(src[1:], src) // overlapping: shift right by one
fmt.Println(src)
s := src[1:3:3]
fmt.Println(len(s), cap(s))
clone := slices.Clone(src) // same as append([]int(nil), src...)
clone[0] = 100
fmt.Println(src[0], clone[0])
}
Output:
0
3 [1 2 3]
[1 1 2 3 4]
2 2
1 100
Common wrong answer: "copy(dst, src) allocates dst if it's too small." It never allocates.
Follow-up: How do you delete element i from a slice? s = slices.Delete(s, i, i+1). Since Go 1.22 it also zeroes the now-unused tail element, so the backing array no longer holds a stale pointer that keeps an object alive.
Q: What is the difference between a nil slice and an empty slice?
var s []int is a nil slice: the pointer is nil, length and capacity are 0. s := []int{} is an empty, non-nil slice: the pointer is non-nil (to a zero-size allocation), length and capacity are 0. len, cap, range and append treat them the same. The difference shows up where code checks == nil, and in serialization: encoding/json encodes a nil slice as null and an empty slice as [].
package main
import (
"encoding/json"
"fmt"
)
func main() {
var nilSlice []string
empty := []string{}
fmt.Println(nilSlice == nil, empty == nil, len(nilSlice), len(empty))
a, _ := json.Marshal(map[string][]string{"tags": nilSlice})
b, _ := json.Marshal(map[string][]string{"tags": empty})
fmt.Println(string(a), string(b))
}
Output:
true false 0 0
{"tags":null} {"tags":[]}
Common wrong answer: "Always return []T{} instead of nil to be safe." Inside Go, prefer nil: it is the zero value and costs nothing. Convert to empty only at an API boundary where a client needs [].
Follow-up: Can you compare two slices with ==? No, only against nil. Use slices.Equal for elements.
Maps
Q: What happens when you write to a nil map? And how do you check whether a key exists?
Reading a nil map returns the zero value, len returns 0, delete is a no-op and range runs zero times. Writing panics with assignment to entry in nil map, because there is no hash table to put the entry in. Struct fields of map type are the usual culprit: the struct's zero value has a nil map.
To tell "missing" apart from "present with the zero value", use the comma-ok form.
package main
import "fmt"
type Counter struct {
counts map[string]int
}
func (c *Counter) Add(k string) {
if c.counts == nil { // lazy init makes the zero value useful
c.counts = make(map[string]int)
}
c.counts[k]++
}
func main() {
var m map[string]int
fmt.Println(m["x"], len(m))
func() {
defer func() { fmt.Println("recovered:", recover()) }()
m["x"] = 1
}()
var c Counter
c.Add("go")
v, ok := c.counts["go"]
_, missing := c.counts["rust"]
fmt.Println(v, ok, missing)
}
Output:
0 0
recovered: assignment to entry in nil map
1 true false
Common wrong answer: "A nil map is the same as an empty map." For reads, yes; for writes, no.
Follow-up: Can you take the address of a map element (&m[k])? No. The map may move its entries when it grows, so element addresses aren't stable. For the same reason m[k].Field = 1 doesn't compile when the values are structs; store pointers or copy, modify, and write back.
Q: Why is map iteration order random?
The language spec says the iteration order is unspecified, and the runtime deliberately starts each range at a random position so programs can't come to depend on any order. Early Go versions had a mostly stable order, people relied on it, and code broke when the implementation changed. The randomization turns "works by accident" into "fails early in tests".
When you need order, collect and sort the keys. Since Go 1.23 the iterator helpers make that one line: slices.Sorted(maps.Keys(m)). Note that fmt prints maps sorted by key, which makes printing deterministic but says nothing about range.
package main
import (
"fmt"
"maps"
"slices"
)
func main() {
m := map[string]int{"b": 2, "a": 1, "c": 3, "d": 4}
for k := range m {
fmt.Print(k, " ") // may print the keys in any order, different each run
}
fmt.Println()
for _, k := range slices.Sorted(maps.Keys(m)) {
fmt.Print(k, "=", m[k], " ")
}
fmt.Println()
fmt.Println(m) // fmt sorts map keys
}
The first line changes between runs. The other two always print:
a=1 b=2 c=3 d=4
map[a:1 b:2 c:3 d:4]
Go 1.24 replaced the map implementation with one based on Swiss tables, which made maps faster. The rule didn't change: no order.
Common wrong answer: "Maps are ordered by insertion" (that's Python and JavaScript), or "order is random, so it's a good source of randomness". It is not uniform and isn't meant to be used that way; use math/rand/v2.
Follow-up: Is it safe to delete keys while ranging over a map? Yes. The spec says an entry removed before it is reached won't be produced. Entries added during iteration may or may not be produced.
Strings, Bytes and Runes
Q: What is a string in Go, and what does len return? What happens when you range over a string?
A string is an immutable sequence of bytes, usually (but not necessarily) valid UTF-8. Under the hood it is a two-word header: a pointer and a length. len(s) is the number of bytes, and s[i] is a byte. A rune is an alias for int32 and holds one Unicode code point. for i, r := range s decodes UTF-8 as it goes: i is the byte offset where each rune starts and r is the rune. Invalid bytes come out as U+FFFD, the replacement character, one byte at a time.
package main
import (
"fmt"
"unicode/utf8"
)
func main() {
s := "héllo, 世界"
fmt.Println(len(s), utf8.RuneCountInString(s))
fmt.Println(s[1], string(s[1]), string([]rune(s)[1]))
for i, r := range "a世b" {
fmt.Printf("%d:%c ", i, r)
}
fmt.Println()
b := []byte(s) // copies: the string stays immutable
b[0] = 'H'
fmt.Println(s[:1], string(b[:1]))
fmt.Println(string(rune(65)), fmt.Sprint(65)) // "A" vs "65"
}
Output:
14 9
195 Ã é
0:a 1:世 4:b
h H
A 65
s[1] is 195, the first byte of the two-byte encoding of é; printed alone as a string it shows up as Ã. To work in characters, convert to []rune or range over the string.
Common wrong answer: "len("世界") is 2." It is 6 bytes. Also wrong: string(65) for number formatting. It produces "A", and go vet warns about it; use strconv.Itoa.
Follow-up: Does []byte(s) always allocate? Semantically it copies. The compiler skips the copy in some cases it can prove safe, such as m[string(b)] lookups and comparisons, but don't depend on that in hot paths without measuring.
Structs, Embedding and Methods
Q: Go has no inheritance. What does embedding give you instead?
Embedding a type inside a struct (writing the type without a field name) promotes its fields and methods to the outer struct. That is composition with automatic delegation, not inheritance: the embedded value is an ordinary field named after its type, there is no "virtual" dispatch back into the outer type, and the outer type is not a subtype of the inner one.
package main
import "fmt"
type Logger struct{ prefix string }
func (l Logger) Log(msg string) { fmt.Println(l.prefix + msg) }
func (l Logger) Hello() { l.Log("hello from " + l.Name()) }
func (l Logger) Name() string { return "Logger" }
type Server struct {
Logger // embedded: Server gets Log, Hello and Name
addr string
}
func (s Server) Name() string { return "Server" } // shadows Logger.Name
func main() {
s := Server{Logger: Logger{prefix: "[srv] "}, addr: ":8080"}
s.Log("starting") // promoted
fmt.Println(s.Name()) // the outer method wins
s.Hello() // Hello calls Logger.Name, not Server.Name
fmt.Println(s.Logger.prefix)
// var l Logger = s // compile error: a Server is not a Logger
}
Output:
[srv] starting
Server
[srv] hello from Logger
[srv]
The third line is the point. In an inheritance language, Hello would call the overriding Name. In Go, Hello has a Logger receiver and knows nothing about Server.
Common wrong answer: "Embedding is inheritance." Interfaces give you polymorphism; embedding gives you reuse. They are separate tools.
Follow-up: What happens if two embedded types both have a method Close? Calling s.Close() is a compile error ("ambiguous selector") unless the outer type defines its own Close. Promotion only works when the name is unambiguous at the shallowest depth.
Q: When do you use a value receiver and when a pointer receiver?
A method's receiver is just its first parameter, so the usual value-vs-pointer rules apply. A value receiver gets a copy: changes don't reach the caller. A pointer receiver gets the address: it can modify the receiver and avoids copying large structs.
Use a pointer receiver when the method mutates, when the struct is large, or when it contains something that must not be copied (sync.Mutex). Use value receivers for small immutable values (time.Time, a Point). Then be consistent: if any method needs a pointer receiver, give all of them pointer receivers, so the method set is predictable.
package main
import "fmt"
type Counter struct{ n int }
func (c Counter) IncValue() { c.n++ } // modifies a copy
func (c *Counter) IncPointer() { c.n++ }
func main() {
var c Counter
c.IncValue()
c.IncPointer() // Go takes &c for you because c is addressable
fmt.Println(c.n)
counters := map[string]Counter{"a": {}}
// counters["a"].IncPointer() // compile error: map elements aren't addressable
tmp := counters["a"]
tmp.IncPointer()
counters["a"] = tmp
fmt.Println(counters["a"].n)
}
Output:
1
1
Common wrong answer: "Pointer receivers are always faster." For small structs a copy is cheap, and pointers can push values to the heap. Choose on semantics first.
Follow-up: Why did c.IncPointer() work on a non-pointer variable? The compiler rewrote it to (&c).IncPointer() because c is addressable. It can't do that for map elements or return values, which is why the commented line fails.
Q: What is a method set, and why doesn't my type satisfy the interface?
The method set of a type decides which interfaces it satisfies. For a type T, it is all methods declared with a T receiver. For *T, it is the methods with T and *T receivers. So if any method that an interface needs has a pointer receiver, only *T satisfies the interface, never T.
The reason: an interface holds a copy of the value. If Go let you call a pointer method on that copy, the mutation would land on the hidden copy and vanish.
package main
import "fmt"
type Shape interface{ Scale(f float64) }
type Square struct{ side float64 }
func (s *Square) Scale(f float64) { s.side *= f }
var _ Shape = (*Square)(nil) // compile-time check: *Square implements Shape
// var _ Shape = Square{} // compile error: Scale has a pointer receiver
func main() {
sq := &Square{side: 2}
var sh Shape = sq
sh.Scale(3)
fmt.Println(sq.side)
}
Output:
6
The var _ Shape = (*Square)(nil) line is a common idiom: it costs nothing at runtime and makes the build fail if someone changes a method's signature.
Common wrong answer: "T and *T have the same methods." You can call pointer methods on addressable T variables, but that is call-site sugar, not part of the method set.
Follow-up: Does *T satisfy an interface whose methods all have value receivers? Yes. The method set of *T includes the value-receiver methods, since Go can always dereference the pointer.
Interfaces
Q: How do interfaces work in Go? What does "implicit satisfaction" mean?
An interface type is a set of method signatures. Any type that has those methods satisfies the interface automatically. There is no implements keyword. This lets the consumer define the interface it needs, after the fact, even for types from packages that have never heard of it. io.Reader has one method, and thousands of types in many packages satisfy it.
Small interfaces are idiomatic ("the bigger the interface, the weaker the abstraction"). A good habit is to accept interfaces in function parameters and return concrete types.
package main
import (
"fmt"
"io"
"strings"
)
// The consumer defines only what it needs.
type reader interface {
Read(p []byte) (int, error)
}
func countBytes(r reader) int {
n, _ := io.Copy(io.Discard, r) // a reader is assignable to io.Reader: same method set
return int(n)
}
type repeat struct {
b byte
n int
}
func (r *repeat) Read(p []byte) (int, error) {
if r.n == 0 {
return 0, io.EOF
}
k := min(len(p), r.n)
for i := range k {
p[i] = r.b
}
r.n -= k
return k, nil
}
func main() {
fmt.Println(countBytes(strings.NewReader("hello"))) // a stdlib type
fmt.Println(countBytes(&repeat{b: 'x', n: 70000})) // our type, never declared to implement anything
}
Output:
5
70000
Common wrong answer: "Define an interface next to every struct, in case you need to mock it." That is Java habit. Define interfaces where they are used, and only when there are, or will soon be, two implementations (a test fake counts).
Follow-up: What is any? An alias for interface{}, the interface with no methods, which every type satisfies. Use it sparingly: it throws away static type checking.
Q: How do type assertions and type switches work?
A type assertion x.(T) gets the concrete value out of an interface. If T is a concrete type, it checks that the dynamic type is exactly T. If T is an interface, it checks that the dynamic type satisfies T. The single-value form panics on failure. The comma-ok form v, ok := x.(T) returns ok == false instead.
A type switch branches on the dynamic type. In each case, the variable has that case's type; in a case listing several types, it keeps the interface type.
package main
import (
"fmt"
"io"
"strings"
)
func describe(x any) string {
switch v := x.(type) {
case nil:
return "nil"
case int, int64:
return fmt.Sprintf("integer %v", v) // v is any here: two types listed
case string:
return "string of length " + fmt.Sprint(len(v)) // v is a string
case io.Reader:
return "a reader"
case error:
return "error: " + v.Error()
default:
return fmt.Sprintf("other %T", v)
}
}
func main() {
fmt.Println(describe(nil), "|", describe(42), "|", describe("héllo"))
fmt.Println(describe(strings.NewReader("")), "|", describe(io.EOF), "|", describe(3.5))
var x any = "go"
n, ok := x.(int)
fmt.Println(n, ok)
defer func() { fmt.Println("recovered:", recover()) }()
_ = x.(int)
}
Output:
nil | integer 42 | string of length 6
a reader | error: EOF | other float64
0 false
recovered: interface conversion: interface {} is string, not int
Cases are tested in order, so put specific types before broad interfaces. A type that is both an io.Reader and an error would match io.Reader here.
Common wrong answer: Using the single-value assertion on data you don't control, which turns a type mismatch into a crash.
Follow-up: How do you check whether a value has an optional method? Assert to a small interface: if s, ok := w.(io.StringWriter); ok { s.WriteString(x) }. The standard library uses this to find fast paths, such as io.Copy checking for WriterTo and ReaderFrom.
Defer, Panic and Recover
Q: When are deferred calls run, and when are their arguments evaluated?
A defer statement schedules a function call to run when the surrounding function returns, whether by return, by falling off the end, or by panicking. Deferred calls run in last-in, first-out order. The arguments, and the function value itself, are evaluated when the defer statement runs, not when the deferred call runs. A closure that reads a variable sees the variable's value at the time it executes.
Deferred closures can also change named result values after return has set them, which is how cleanup errors get reported.
package main
import (
"errors"
"fmt"
)
func order() {
for i := range 3 {
defer fmt.Print(i, " ") // i is evaluated now
}
x := 1
defer fmt.Println("arg:", x) // captured value: 1
defer func() { fmt.Println("closure:", x) }() // reads x at the end: 2
x = 2
}
func save() (err error) {
defer func() {
if cerr := closeFile(); cerr != nil && err == nil {
err = cerr // a deferred closure can change a named result
}
}()
return nil
}
func closeFile() error { return errors.New("close failed") }
func main() {
order()
fmt.Println()
fmt.Println(save())
}
Output:
closure: 2
arg: 1
2 1 0
close failed
Common wrong answer: "defer runs at the end of the block" (it's the function), or "deferred arguments are evaluated at the end".
Follow-up: Is defer slow? It used to cost tens of nanoseconds. Since Go 1.14, "open-coded" defers make most of them nearly free; a defer inside a loop still uses the slower path, which is one more reason to avoid it there (see the Senior section).
Q: How do panic and recover work?
panic stops normal execution of the current goroutine. The goroutine unwinds its stack, running deferred calls as it goes. If a deferred function calls recover(), the panic stops, recover returns the panic value, and the function containing that defer returns normally to its caller. If nothing recovers, the program prints the panic value and a stack trace and exits with status 2.
recover only does something when it is called directly by a deferred function while a panic is in flight. Anywhere else it returns nil.
package main
import "fmt"
func safeDiv(a, b int) (q int, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("recovered: %v", r)
}
}()
return a / b, nil
}
func helper() any { return recover() } // not called directly by the deferred function
func notDirect() (got any) {
defer func() {
got = helper()
recover() // stop the panic so the program continues
}()
panic("boom")
}
func main() {
fmt.Println(safeDiv(10, 2))
fmt.Println(safeDiv(1, 0))
fmt.Println(notDirect())
}
Output:
5 <nil>
0 recovered: runtime error: integer divide by zero
<nil>
Use panics for programmer errors and truly impossible states, not for expected failures like "file not found". Those are errors, returned as values.
Common wrong answer: "recover works like catch anywhere in the call chain." It only works in a deferred function, in the same goroutine as the panic.
Follow-up: Can you recover from every failure? No. Runtime fatal errors such as concurrent map writes, running out of memory, or "all goroutines are asleep - deadlock!" kill the process without unwinding, and recover never sees them.
Errors
Q: How do you wrap errors, and what do errors.Is and errors.As do?
Errors in Go are values that implement Error() string. To add context while keeping the original error inspectable, wrap it with fmt.Errorf and the %w verb. That builds a chain. errors.Is(err, target) walks the chain looking for a value equal to target (typically a sentinel like io.EOF). errors.As(err, &target) walks the chain looking for an error of target's type and stores it. Go 1.26 added a generic version, errors.AsType[T](err), that returns the value and a bool without the pointer dance.
package main
import (
"errors"
"fmt"
"io/fs"
"os"
)
var ErrNotFound = errors.New("not found") // sentinel
type ValidationError struct{ Field string } // typed error
func (e *ValidationError) Error() string { return "invalid " + e.Field }
func find(id int) error {
if id < 0 {
return &ValidationError{Field: "id"}
}
return fmt.Errorf("find user %d: %w", id, ErrNotFound)
}
func main() {
err := fmt.Errorf("handler: %w", find(7))
fmt.Println(err)
fmt.Println(errors.Is(err, ErrNotFound), err == ErrNotFound)
err = fmt.Errorf("handler: %w", find(-1))
var ve *ValidationError
if errors.As(err, &ve) {
fmt.Println("field:", ve.Field)
}
if ve2, ok := errors.AsType[*ValidationError](err); ok { // Go 1.26
fmt.Println("field again:", ve2.Field)
}
_, err = os.Open("/definitely/missing")
fmt.Println(errors.Is(err, fs.ErrNotExist))
lost := fmt.Errorf("handler: %v", ErrNotFound) // %v flattens to text
fmt.Println(errors.Is(lost, ErrNotFound))
}
Output:
handler: find user 7: not found
true false
field: id
field again: id
true
false
Common wrong answer: Comparing with == (fails as soon as someone wraps the error) or matching on err.Error() strings (breaks when the message changes).
Follow-up: Should you always wrap with %w? No. Wrapping makes the inner error part of your API: callers can now depend on it. Use %v when you want to hide an implementation detail (for example, don't leak a *pq.Error out of your storage layer).
Closures and Loops
Q: What is a closure, and what changed about loop variables in Go 1.22?
A closure is a function literal that refers to variables from the enclosing function. It captures the variables, not copies of their values, so it sees later changes and can make its own. Captured variables move to the heap if they outlive the function.
Before Go 1.22, a for loop had one variable for the whole loop, updated each iteration. Every closure or goroutine created in the loop captured that same variable, and usually saw its final value. Go 1.22 changed for loops so that each iteration gets a new variable. The new behavior is tied to the go line in the module's go.mod: modules that declare go 1.22 or later get per-iteration variables; older modules keep the old behavior, so nothing broke silently.
package main
import "fmt"
func counter() func() int {
n := 0
return func() int { n++; return n } // n outlives counter: it lives on the heap
}
func main() {
next := counter()
fmt.Println(next(), next(), next())
var prints []func()
for i := 0; i < 3; i++ {
prints = append(prints, func() { fmt.Print(i, " ") })
}
for _, p := range prints {
p()
}
fmt.Println()
}
With go 1.22 or later in go.mod, this prints:
1 2 3
0 1 2
Under the old semantics the second line was 3 3 3. The pre-1.22 fix was to shadow the variable, i := i, inside the loop body. That line is now redundant, and go fix in Go 1.26 can remove it for you. Part 5 has a puzzle that shows both behaviors side by side.
Common wrong answer: "Closures capture values." They capture variables. The Go 1.22 change only gives each iteration a fresh variable; inside one iteration, a closure still sees updates to it.
Follow-up: Did Go 1.22 change anything else about loops? Yes, for i := range 10 (range over an integer) arrived in the same release, and Go 1.23 added range over iterator functions (see Senior).
First Goroutines and Channels
Q: What is a goroutine, and what happens to running goroutines when main returns?
A goroutine is a function running concurrently with the rest of the program, started with the go keyword. It is managed by the Go runtime, not the OS: it starts with a small stack (a few KB) that grows as needed, so a program can run hundreds of thousands of them. When main returns, the program exits immediately; other goroutines are not waited for and their deferred calls don't run. You must wait for them explicitly.
package main
import (
"fmt"
"sync"
)
func main() {
go fmt.Println("may never print") // main might exit first
var wg sync.WaitGroup
results := make([]int, 5)
for i := range 5 {
wg.Go(func() { // Go 1.25: Add(1), go, and Done in one call
results[i] = i * i // each goroutine writes its own index: no race
})
}
wg.Wait()
fmt.Println(results)
}
This always prints [0 1 4 9 16] on its last line. The first line may or may not appear, and if it does, its position relative to the slice can vary.
Common wrong answer: "Add time.Sleep to wait for goroutines." Sleeping is a guess, and it fails under load. Use sync.WaitGroup, a channel, or errgroup. And with the older wg.Add(1) / defer wg.Done() style, call Add before the go statement: calling it inside the goroutine lets Wait return early. wg.Go makes that mistake impossible, and since Go 1.25 the go vet waitgroup check flags it.
Follow-up: What happens if a goroutine panics and nobody recovers? The whole program crashes, not just that goroutine. See the panic-across-goroutines question in Senior.
Q: What is the difference between buffered and unbuffered channels?
An unbuffered channel (make(chan T)) has no storage. A send blocks until a receiver takes the value, and a receive blocks until a sender provides one, so each transfer is a rendezvous: when the send completes, you know the receiver has the value. A buffered channel (make(chan T, n)) has a queue of n slots. Sends block only when the buffer is full and receives only when it is empty. The sender learns nothing about when the value is consumed.
package main
import (
"fmt"
"time"
)
func main() {
unbuf := make(chan string)
go func() {
time.Sleep(20 * time.Millisecond)
fmt.Println("receiver ready")
fmt.Println("got", <-unbuf)
}()
start := time.Now()
unbuf <- "ping" // blocks until the receiver takes it
fmt.Println("send done after receiver:", time.Since(start) >= 20*time.Millisecond)
buf := make(chan int, 2)
buf <- 1
buf <- 2 // doesn't block: the buffer has room
fmt.Println(len(buf), cap(buf))
select {
case buf <- 3:
fmt.Println("sent 3")
default:
fmt.Println("buffer full, would block")
}
time.Sleep(10 * time.Millisecond) // let the receiver print "got ping" before exit
}
Output (the "got ping" line may also land after "send done", since the two goroutines race to print):
receiver ready
got ping
send done after receiver: true
2 2
buffer full, would block
Use unbuffered channels when you want a handoff guarantee. Use a small buffer to absorb bursts or to let a known number of senders finish without waiting (for example, a buffer of 1 for a result that might never be read). A large buffer usually hides a slow consumer rather than fixing it.
Common wrong answer: "Buffered channels are faster, so always add a buffer." A buffer changes semantics and can hide deadlocks until production load fills it.
Follow-up: Why do people make a buffered channel of size 1 for a goroutine's result? So the goroutine can send and exit even if the caller has already given up (timed out). With an unbuffered channel, that goroutine would block forever: a leak.
Q: Who should close a channel, and what happens when you use a closed channel?
The sender closes, never the receiver, and only when it needs to tell receivers that no more values are coming (for example, to end a range loop). Closing is not required for garbage collection. The rules:
| Operation | nil channel | open channel | closed channel |
|---|---|---|---|
| send | blocks forever | blocks or succeeds | panic |
| receive | blocks forever | blocks or succeeds | returns remaining buffered values, then zero value with ok == false immediately |
| close | panic | succeeds | panic |
package main
import "fmt"
func main() {
ch := make(chan int, 3)
ch <- 1
ch <- 2
close(ch)
for v := range ch { // drains the buffer, then stops
fmt.Print(v, " ")
}
fmt.Println()
v, ok := <-ch
fmt.Println(v, ok)
func() {
defer func() { fmt.Println("recovered:", recover()) }()
ch <- 3
}()
func() {
defer func() { fmt.Println("recovered:", recover()) }()
close(ch)
}()
}
Output:
1 2
0 false
recovered: send on closed channel
recovered: close of closed channel
With several senders, no single sender knows when it is safe to close. Use a sync.WaitGroup and close from one extra goroutine after wg.Wait(), or signal shutdown with a separate done channel or a context instead of closing the data channel.
Common wrong answer: "Always close channels when you're done, like files." Unclosed channels are garbage-collected like anything else. Close is a signal, not cleanup.
Follow-up: How do you broadcast "stop" to many goroutines? Close a channel that they all receive from (<-done). Receiving from a closed channel succeeds immediately for every receiver. That is exactly how ctx.Done() works.
Q: How do you put a timeout on a channel operation?
select waits on several channel operations and runs whichever is ready first. Add a case that receives from a timer channel and you have a timeout. If more than one case is ready, select picks one uniformly at random, so no case can starve the others. A default case makes the select non-blocking.
package main
import (
"fmt"
"time"
)
func slow(d time.Duration) <-chan string {
ch := make(chan string, 1) // buffered: the sender can exit even if nobody reads
go func() {
time.Sleep(d)
ch <- "done after " + d.String()
}()
return ch
}
func main() {
select {
case r := <-slow(10 * time.Millisecond):
fmt.Println(r)
case <-time.After(100 * time.Millisecond):
fmt.Println("timeout")
}
select {
case r := <-slow(200 * time.Millisecond):
fmt.Println(r)
case <-time.After(50 * time.Millisecond):
fmt.Println("timeout")
}
}
Output:
done after 10ms
timeout
In real services prefer a context.Context with a deadline (Senior section), since it propagates through every call that accepts a context. And before Go 1.23, calling time.After in a loop was a well-known memory leak: each timer stayed alive until it fired. Since Go 1.23, unreferenced timers are garbage-collected even if they haven't fired, so the leak is gone for modules on go 1.23 or later, though a reused time.Timer is still cheaper in a hot loop.
Common wrong answer: "select checks the cases top to bottom." The order in the source doesn't matter; the choice among ready cases is random.
Follow-up: What does an empty select {} do? It blocks forever. Occasionally used at the end of main in a program whose real work is in other goroutines.
Part 2: Senior
Interfaces in Depth
Q: Why can a function that returns a nil pointer make err != nil true?
An interface value is a pair: a type word (which concrete type is stored) and a data word (the value or a pointer to it). An interface is nil only when both are nil. If you store a nil *MyErr in an error, the type word says *MyErr, so the interface is not nil, even though the pointer inside is.
package main
import "fmt"
type MyErr struct{}
func (*MyErr) Error() string { return "my error" }
func validate(ok bool) error {
var p *MyErr // nil pointer
if !ok {
p = &MyErr{}
}
return p // BUG: always a non-nil interface
}
func validateFixed(ok bool) error {
if !ok {
return &MyErr{}
}
return nil // return a literal nil interface
}
func main() {
err := validate(true)
fmt.Println(err == nil)
fmt.Printf("%T %v\n", err, err == (*MyErr)(nil))
fmt.Println(validateFixed(true) == nil)
}
Output:
false
*main.MyErr true
true
Common wrong answer: "Go has a bug in nil comparison." It's working as designed: nil for an interface means "no type at all".
Follow-up: How do you avoid it? Return the error interface type from functions, never a concrete error pointer type, and return a literal nil on success. staticcheck and nilness flag some cases.
Second follow-up: Can comparing two interfaces panic? Yes. == on interfaces compares dynamic types, then values; if the dynamic type is a slice, map or func, it panics at runtime with comparing uncomparable type []int. The same happens when such a value is used as a map[any]T key.
Generics
Q: How do generics work in Go? What are constraints and type sets?
Since Go 1.18, functions and types can take type parameters. Each type parameter has a constraint, which is an interface. An interface used as a constraint describes a type set: the set of types allowed. Method elements (String() string) require methods; type elements (int | float64) list allowed types; a tilde (~int) means "any type whose underlying type is int", so your own type Celsius float64 is included.
The standard library gives you any, comparable (types that support ==) and cmp.Ordered (types that support <).
package main
import (
"cmp"
"fmt"
)
type Number interface {
~int | ~int64 | ~float64
}
func Sum[T Number](xs []T) T {
var total T
for _, x := range xs {
total += x
}
return total
}
func MaxOf[T cmp.Ordered](first T, rest ...T) T {
m := first
for _, v := range rest {
m = max(m, v)
}
return m
}
type Stack[T any] struct{ items []T }
func (s *Stack[T]) Push(v T) { s.items = append(s.items, v) }
func (s *Stack[T]) Pop() (T, bool) {
var zero T
if len(s.items) == 0 {
return zero, false
}
v := s.items[len(s.items)-1]
s.items = s.items[:len(s.items)-1]
return v, true
}
type Celsius float64
func main() {
fmt.Println(Sum([]int{1, 2, 3}), Sum([]Celsius{20.5, 1.5}))
fmt.Println(MaxOf("pear", "apple", "zebra"))
var s Stack[string]
s.Push("a")
s.Push("b")
v, ok := s.Pop()
fmt.Println(v, ok)
}
Output:
6 22
zebra
b true
Limits worth knowing: methods can't declare their own type parameters (only the type can); an interface with type elements can only be used as a constraint, not as a variable's type; and Go 1.26 now lets a generic type refer to itself in its own constraint (type Adder[A Adder[A]] interface{ Add(A) A }).
Common wrong answer: "Go generics are like C++ templates: one copy of the code per type." Go uses GC shape stenciling: one instantiation per memory "shape" (all pointer types share one), plus a dictionary passed at runtime. That keeps binaries small, but calls through a type parameter's methods can be slower than direct calls.
Follow-up: Why doesn't func Sum[T any](xs []T) T compile with total += x? Because any's type set includes types without +. The constraint must guarantee every operation you use.
Q: When should you not use generics?
Reach for generics when you are writing the same code for different types: containers, slices/maps-style helpers, typed wrappers around sync.Map or atomic.Pointer. Don't use them when:
- An interface already expresses it. If the function only calls methods, take the interface.
func Save(w io.Writer)is clearer thanfunc Save[W io.Writer](w W)and no slower in practice. - There is only one type. Writing
Repository[T]for a singleUsertype is ceremony. - The behavior differs per type. If you'd write a type switch inside the generic function, you want an interface with a method.
- Hot paths call methods on the type parameter. Measure; the dictionary-based dispatch can block inlining.
package main
import (
"fmt"
"io"
"os"
"strings"
)
// Good: the interface says everything needed. No type parameter.
func greet(w io.Writer, name string) { fmt.Fprintf(w, "hello, %s\n", name) }
// Good use of generics: identical logic, many element types.
func Filter[T any](xs []T, keep func(T) bool) []T {
var out []T
for _, x := range xs {
if keep(x) {
out = append(out, x)
}
}
return out
}
func main() {
greet(os.Stdout, "gopher")
var sb strings.Builder
greet(&sb, "builder")
fmt.Print(sb.String())
fmt.Println(Filter([]int{1, 2, 3, 4}, func(n int) bool { return n%2 == 0 }))
}
Output:
hello, gopher
hello, builder
[2 4]
Common wrong answer: "Generics are always faster than interfaces because there's no boxing." Sometimes; sometimes slower. It depends on the shape and whether the call inlines.
Follow-up: Before generics, how did Go do containers? With interface{} and type assertions (container/list, sync.Map), giving up compile-time type safety.
Iterators
Q: How do range-over-function iterators work (Go 1.23)?
Since Go 1.23, for range accepts functions of three shapes: func(yield func() bool), func(yield func(V) bool) and func(yield func(K, V) bool). The iter package names the last two iter.Seq[V] and iter.Seq2[K, V]. The compiler turns the loop body into the yield function. Each call to yield runs the body once; when the body hits break or return, yield returns false, and the iterator must stop calling it.
package main
import (
"fmt"
"iter"
"maps"
"slices"
)
func Countdown(from int) iter.Seq[int] {
return func(yield func(int) bool) {
for i := from; i > 0; i-- {
if !yield(i) {
return // the loop body said stop
}
}
}
}
func bad(yield func(int) bool) {
yield(1)
yield(2) // ignores the false returned after break
}
func main() {
for n := range Countdown(5) {
if n == 2 {
break
}
fmt.Print(n, " ")
}
fmt.Println()
ages := map[string]int{"bo": 31, "al": 25}
fmt.Println(slices.Sorted(maps.Keys(ages)))
fmt.Println(slices.Collect(Countdown(3)))
defer func() { fmt.Println("recovered:", recover()) }()
for v := range bad {
fmt.Println("got", v)
break
}
}
Output:
5 4 3
[al bo]
[3 2 1]
got 1
recovered: runtime error: range function continued iteration after function for loop body returned false
These are push iterators: the iterator drives the loop. iter.Pull converts one into a pull iterator (next, stop := iter.Pull(seq)) when you need to step two sequences in lockstep. Always call stop when you finish early.
Common wrong answer: "Iterators run in a separate goroutine like Python generators." Push iterators are plain function calls on the same goroutine. Only iter.Pull uses a coroutine-style switch under the hood.
Follow-up: Why not just return a slice? Iterators avoid building the whole slice: they can stream lines from a file, walk a tree lazily, or stop early, with no allocation for the result.
Error Design
Q: Sentinel errors, typed errors, or opaque errors? And what is errors.Join for?
Three styles, each with a cost:
| Style | Example | Caller checks with | Coupling |
|---|---|---|---|
| Sentinel | var ErrNotFound = errors.New(...) | errors.Is | The variable becomes public API |
| Typed | type *ValidationError struct{...} | errors.As / errors.AsType | The type and its fields become API |
| Opaque | fmt.Errorf("...: %v", err) | Only err != nil | None: you can change anything |
A sensible default: opaque errors for most internal failures, a few sentinels for conditions callers really branch on (not found, conflict), and typed errors when callers need structured data (the field that failed, a retry-after duration). You can also give a type an Is(target error) bool method so it matches a sentinel.
errors.Join (Go 1.20) combines several errors into one. Is and As search all of them, and Error() joins the messages with newlines. It is handy for validation and for cleanup that can fail in several places.
package main
import (
"errors"
"fmt"
)
var ErrTemporary = errors.New("temporary")
type HTTPError struct{ Code int }
func (e HTTPError) Error() string { return fmt.Sprintf("http %d", e.Code) }
// 503 counts as temporary without wrapping ErrTemporary.
func (e HTTPError) Is(target error) bool { return target == ErrTemporary && e.Code == 503 }
func validate(name string, age int) error {
var errs []error
if name == "" {
errs = append(errs, errors.New("name is required"))
}
if age < 0 {
errs = append(errs, fmt.Errorf("age %d: %w", age, ErrTemporary))
}
return errors.Join(errs...) // nil when errs is empty
}
func main() {
fmt.Println(errors.Is(HTTPError{503}, ErrTemporary), errors.Is(HTTPError{404}, ErrTemporary))
err := validate("", -1)
fmt.Println(err)
fmt.Println(errors.Is(err, ErrTemporary), validate("ana", 3) == nil)
}
Output:
true false
name is required
age -1: temporary
true true
Common wrong answer: "Panic for errors and recover at the top, like exceptions." Panics skip the explicit control flow that makes Go code reviewable.
Follow-up: Can fmt.Errorf wrap more than one error? Yes, since Go 1.20 a format string can contain several %w verbs, giving the same multi-error behavior as errors.Join.
Defer and Panic in Depth
Q: What goes wrong with defer inside a loop?
Deferred calls run when the function returns, not at the end of each iteration. A loop that opens a file and defers its close keeps every file open until the loop's function finishes, so a long loop runs out of file descriptors or connections. Wrap the body in a function (or move it to a helper) so each iteration's defers run at the end of that iteration.
package main
import "fmt"
var open int
type res struct{}
func acquire() *res { open++; return &res{} }
func (r *res) Close() { open-- }
func leaky(n int) (peak int) {
for range n {
r := acquire()
defer r.Close() // runs only when leaky returns
peak = max(peak, open)
}
return peak
}
func fixed(n int) (peak int) {
for range n {
func() {
r := acquire()
defer r.Close() // runs at the end of each iteration
peak = max(peak, open)
}()
}
return peak
}
func main() {
fmt.Println("leaky peak:", leaky(1000))
fmt.Println("fixed peak:", fixed(1000))
fmt.Println("open now:", open)
}
Output:
leaky peak: 1000
fixed peak: 1
open now: 0
Common wrong answer: "It's fine because they all close eventually." Eventually is after you've hit too many open files.
Follow-up: What about defer mu.Unlock() in a loop? Worse: the second iteration's Lock deadlocks against the first iteration's still-held lock.
Q: Can you recover a panic that happened in another goroutine?
No. recover only stops a panic in its own goroutine. A panic that reaches the top of any goroutine's stack crashes the whole process, whatever main does. So every goroutine you start in a long-running server must either be panic-free or install its own defer/recover. net/http does this for each request handler (it logs the panic and closes the connection); your own background goroutines get no such protection.
package main
import (
"fmt"
"sync"
)
// safeGo runs f in a goroutine and turns a panic into an error.
func safeGo(wg *sync.WaitGroup, errs chan<- error, f func()) {
wg.Go(func() {
defer func() {
if r := recover(); r != nil {
errs <- fmt.Errorf("goroutine panicked: %v", r)
}
}()
f()
})
}
func main() {
var wg sync.WaitGroup
errs := make(chan error, 1)
safeGo(&wg, errs, func() {
var m map[string]int
m["boom"] = 1
})
wg.Wait()
close(errs)
for err := range errs {
fmt.Println(err)
}
}
Output:
goroutine panicked: assignment to entry in nil map
Without the deferred recover the program would print panic: assignment to entry in nil map with a stack trace and exit with status 2 (Part 5 shows that).
Common wrong answer: "Put a recover in main and you're covered." main's defers only see panics on the main goroutine.
Follow-up: Should you recover everywhere? No. Recover at boundaries (per request, per job) where you can report and keep serving. A panic means state may be corrupted; recovering deep inside a library hides bugs.
Package Initialization and Design
Q: In what order does a Go program initialize?
- Imported packages initialize first, depth-first, each exactly once no matter how many packages import it.
- Inside a package, package-level variables initialize in dependency order: a variable is initialized after the variables its initializer refers to, regardless of where they appear in the source. Variables without dependencies go in declaration order (files in the order the go tool passes them, which is sorted by filename).
- Then every
init()function runs, in the order they appear (a file may have several). - Finally
main.mainruns.
package main
import "fmt"
var a = b + 1 // depends on b, so b is initialized first
var b = f()
func f() int {
fmt.Println("init b")
return 1
}
func init() { fmt.Println("init 1, a =", a) }
func init() { fmt.Println("init 2") }
func main() { fmt.Println("main") }
Output:
init b
init 1, a = 2
init 2
main
For package design, init is best kept for registering things that can't fail (database/sql drivers, image formats). Anything that can fail, reads the environment or touches the network belongs in an explicit constructor that returns an error: init can't return one, it runs in tests too, and it makes the import itself a side effect. Prefer packages organized by what they provide (billing, auth) over layers (models, utils); use internal/ to stop other modules importing your internals; and remember import cycles are a compile error, so dependencies must form a tree.
Common wrong answer: "Package variables initialize top to bottom." Only when there are no dependencies between them.
Follow-up: What does a blank import import _ "net/http/pprof" do? It runs that package's init (which registers the /debug/pprof/ handlers on http.DefaultServeMux) without using any name from it.
The Scheduler
Q: How do goroutines differ from OS threads? Explain the GMP model.
An OS thread has a fixed stack (often 1 to 8 MB reserved), and creating or switching one goes through the kernel, costing microseconds. A goroutine starts with a small growable stack (a few KB), and switching between goroutines happens in user space, costing much less. The runtime multiplexes many goroutines onto a few threads using three kinds of object:
- G: a goroutine, with its stack and saved registers.
- M: a machine, meaning an OS thread.
- P: a processor, a scheduling context with a local run queue. There are
GOMAXPROCSPs, so at most that many goroutines run Go code at once.
flowchart TB
GQ["Global run queue"] --> P1
subgraph P1["P1 (local queue)"]
G1["G running"]
G2["G runnable"]
G3["G runnable"]
end
subgraph P2["P2 (local queue)"]
G4["G running"]
end
P1 --> M1["M1 (OS thread)"]
P2 --> M2["M2 (OS thread)"]
P2 -.->|"steals half when empty"| P1
M3["M3 blocked in syscall"] -.->|"hands off its P"| P2
An M needs a P to run Go code. When a P's queue is empty, it steals work from other Ps (work stealing). When a goroutine blocks in a system call, its M blocks with it, and the P is handed to another M so other goroutines keep running. Network I/O doesn't block an M at all: it parks the goroutine on the netpoller (epoll, kqueue, IOCP) and resumes it when the socket is ready. Since Go 1.14 the scheduler can also preempt a goroutine stuck in a tight loop by sending its thread a signal.
package main
import (
"fmt"
"runtime"
"sync"
)
func main() {
fmt.Println("GOMAXPROCS = NumCPU:", runtime.GOMAXPROCS(0) == runtime.NumCPU())
var wg sync.WaitGroup
start := make(chan struct{})
for range 100_000 {
wg.Go(func() { <-start }) // 100k parked goroutines
}
fmt.Println("goroutines:", runtime.NumGoroutine())
close(start)
wg.Wait()
fmt.Println("after:", runtime.NumGoroutine())
}
Output (the first line is false inside a container whose CPU limit is lower than the host's core count):
GOMAXPROCS = NumCPU: true
goroutines: 100001
after: 1
Go Concurrency walks through the scheduler in more detail.
Common wrong answer: "Goroutines are green threads that can't use multiple cores." They run in parallel on up to GOMAXPROCS cores.
Follow-up: What changed about GOMAXPROCS in Go 1.25? On Linux it now defaults to the cgroup CPU limit if that is lower than the core count, and the runtime re-checks it periodically. Before that, a pod limited to 2 CPUs on a 64-core node ran 64 Ps and got throttled; teams used go.uber.org/automaxprocs to fix it.
Channels and Select in Depth
Q: What does a nil channel do in a select, and why is that useful?
Sending to or receiving from a nil channel blocks forever. In a select, that means a case on a nil channel can never be chosen. Setting a channel variable to nil is the standard way to switch off a case, for example once that input has been closed, while still waiting on the others.
package main
import (
"fmt"
"slices"
)
func merge(a, b <-chan int) []int {
var out []int
for a != nil || b != nil {
select {
case v, ok := <-a:
if !ok {
a = nil // closed: disable this case
continue
}
out = append(out, v)
case v, ok := <-b:
if !ok {
b = nil
continue
}
out = append(out, v)
}
}
return out
}
func gen(vals ...int) <-chan int {
ch := make(chan int)
go func() {
defer close(ch)
for _, v := range vals {
ch <- v
}
}()
return ch
}
func main() {
got := merge(gen(1, 3, 5), gen(2, 4))
slices.Sort(got) // arrival order between the two inputs varies
fmt.Println(got)
}
Output:
Without the = nil, a closed channel is always ready (it returns the zero value), so the loop would spin, appending zeros or burning CPU.
Common wrong answer: "Receiving from a nil channel panics." Closing a nil channel panics; sending or receiving just blocks.
Follow-up: How else can you use this? To apply backpressure: set the output channel to nil while you have nothing to send, and the input channel to nil while your buffer is full.
Q: Explain context: cancellation, deadlines and the rules for using it.
A context.Context carries a cancellation signal, an optional deadline and request-scoped values across API boundaries and goroutines. Contexts form a tree: WithCancel, WithTimeout, WithDeadline and WithCancelCause derive a child, and cancelling a parent cancels every descendant. Work checks <-ctx.Done() in a select, then reports ctx.Err(): context.Canceled or context.DeadlineExceeded. context.Cause(ctx) returns the specific reason passed to a cause-aware cancel function.
The rules: pass the context as the first parameter, named ctx; don't store it in a struct; always call the cancel function (usually defer cancel()), or the child's timer and resources live until the parent ends; use values only for request-scoped data like trace IDs, never for optional parameters.
package main
import (
"context"
"errors"
"fmt"
"time"
)
func work(ctx context.Context, d time.Duration) error {
select {
case <-time.After(d):
return nil
case <-ctx.Done():
return ctx.Err()
}
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
defer cancel()
fmt.Println(work(ctx, 10*time.Millisecond))
fmt.Println(work(ctx, time.Second))
parent, cancelParent := context.WithCancelCause(context.Background())
child, cancelChild := context.WithTimeout(parent, time.Hour)
defer cancelChild()
cancelParent(errors.New("user logged out"))
<-child.Done() // the parent's cancellation reached the child
fmt.Println(child.Err(), "|", context.Cause(child))
stop := context.AfterFunc(ctx, func() { fmt.Println("cleanup after ctx ends") })
defer stop()
time.Sleep(10 * time.Millisecond)
}
Output:
<nil>
context deadline exceeded
context canceled | user logged out
cleanup after ctx ends
The last line comes from context.AfterFunc (Go 1.21): because ctx had already expired, it ran the function right away in its own goroutine. In tests, use t.Context() (Go 1.24), which is cancelled just before the test's cleanup functions run.
Common wrong answer: "Cancelling a context stops the goroutine." Cancellation is cooperative. If the code never checks ctx.Done() or passes ctx to a call that does, nothing stops.
Follow-up: How do you keep going after the request is cancelled, say to write an audit log? context.WithoutCancel(ctx) (Go 1.21) keeps the values but drops the cancellation.
The sync Package
Q: Mutex or RWMutex? And what goes wrong when you copy one?
A sync.Mutex gives exclusive access. A sync.RWMutex allows many readers at once (RLock) or one writer (Lock). RWMutex helps only when reads greatly outnumber writes and critical sections are long enough to matter; it costs more per operation than Mutex, so with tiny critical sections it is often slower. Benchmark before switching.
A mutex must not be copied after first use: the copy has its own state, so two copies protect nothing. That happens through value receivers, passing a struct by value, or ranging over a slice of structs by value. go vet's copylocks check catches most cases. Also, Go's mutexes are not reentrant: locking twice in the same goroutine deadlocks, and so does taking RLock again while a writer is waiting.
package main
import (
"fmt"
"sync"
)
type Stats struct {
mu sync.RWMutex
hits map[string]int
}
func (s *Stats) Inc(k string) { // pointer receiver: one shared mutex
s.mu.Lock()
defer s.mu.Unlock()
if s.hits == nil {
s.hits = map[string]int{}
}
s.hits[k]++
}
func (s *Stats) Get(k string) int {
s.mu.RLock()
defer s.mu.RUnlock()
return s.hits[k]
}
func main() {
var s Stats
var wg sync.WaitGroup
for range 50 {
wg.Go(func() {
for range 100 {
s.Inc("home")
_ = s.Get("home")
}
})
}
wg.Wait()
fmt.Println(s.Get("home"))
}
Output:
5000
Common wrong answer: "RWMutex is always better for read-heavy code." It depends on the length of the critical section and the core count; measure.
Follow-up: Is sync.Mutex fair? Mostly not, for speed: a running goroutine can grab the lock ahead of a woken waiter. If a waiter has waited more than 1 ms, the mutex switches to starvation mode and hands the lock directly to waiters in FIFO order until the queue is short again.
Q: What are sync.Once, OnceFunc and OnceValue for?
sync.Once runs a function exactly once, even when many goroutines call it at the same time; the others wait until the first call finishes. It is the standard way to do lazy, thread-safe initialization. Go 1.21 added sync.OnceFunc, sync.OnceValue and sync.OnceValues, which wrap a function and return a new function that runs the original once and caches its results. If the function panics, every later call panics with the same value instead of silently returning zero values.
package main
import (
"fmt"
"sync"
)
var loadConfig = sync.OnceValues(func() (map[string]string, error) {
fmt.Println("loading config")
return map[string]string{"env": "prod"}, nil
})
func main() {
var wg sync.WaitGroup
for range 10 {
wg.Go(func() {
cfg, err := loadConfig()
if err != nil || cfg["env"] != "prod" {
panic("bad config")
}
})
}
wg.Wait()
cfg, _ := loadConfig()
fmt.Println(cfg["env"])
}
Output:
loading config
prod
Common wrong answer: Hand-rolled double-checked locking with a plain bool (if !initialized { mu.Lock() ... }). Reading the bool outside the lock is a data race; sync.Once does this correctly with an atomic.
Follow-up: What if initialization fails and you want to retry later? Once never retries. Use a mutex with explicit state, or cache the error and let callers decide.
Q: When do you use sync/atomic?
Atomics give lock-free reads and writes of single words: counters, flags, and swapping a pointer to an immutable value (a config snapshot). Since Go 1.19, prefer the typed versions (atomic.Int64, atomic.Bool, atomic.Pointer[T]): they can't be accidentally accessed non-atomically, and they're aligned correctly even on 32-bit platforms. CompareAndSwap is the building block for lock-free updates.
Atomics coordinate a single value. As soon as an invariant spans two fields ("count matches len(items)"), use a mutex.
package main
import (
"fmt"
"sync"
"sync/atomic"
)
type Config struct{ Version int }
func main() {
var hits atomic.Int64
var wg sync.WaitGroup
for range 100 {
wg.Go(func() {
for range 1000 {
hits.Add(1)
}
})
}
wg.Wait()
fmt.Println(hits.Load())
var cfg atomic.Pointer[Config]
cfg.Store(&Config{Version: 1})
old := cfg.Load()
swapped := cfg.CompareAndSwap(old, &Config{Version: 2}) // publish a new snapshot
fmt.Println(swapped, cfg.Load().Version, old.Version)
}
Output:
100000
true 2 1
Common wrong answer: "Atomics make everything thread-safe." Two atomic operations in a row are not atomic together: if x.Load() == 0 { x.Store(1) } is a race; use CompareAndSwap(0, 1).
Follow-up: What ordering do Go atomics give? Sequentially consistent, as stated in the Go memory model. Go has no relaxed or acquire/release atomics.
Q: What does errgroup add over a WaitGroup?
golang.org/x/sync/errgroup runs a group of goroutines and returns the first error. errgroup.WithContext also returns a context that is cancelled as soon as any goroutine fails (or when Wait returns), so the others can stop early. SetLimit(n) caps how many goroutines run at once: Go blocks until a slot frees up, which makes it a bounded worker pool in one line.
package main
import (
"context"
"errors"
"fmt"
"time"
"golang.org/x/sync/errgroup"
)
func fetch(ctx context.Context, id int) error {
if id == 3 {
return errors.New("fetch 3 failed")
}
select {
case <-time.After(100 * time.Millisecond):
return nil
case <-ctx.Done():
return ctx.Err() // cancelled because id 3 failed
}
}
func main() {
g, ctx := errgroup.WithContext(context.Background())
g.SetLimit(4)
start := time.Now()
for id := range 8 {
g.Go(func() error { return fetch(ctx, id) })
}
err := g.Wait()
fmt.Println(err, "| fast:", time.Since(start) < 150*time.Millisecond)
}
Output:
fetch 3 failed | fast: true
Common wrong answer: "errgroup collects all errors." It keeps only the first. Use errors.Join over a slice (one slot per goroutine) if you need all of them.
Follow-up: Does errgroup recover panics? No. A panic in a g.Go function still crashes the program.
Q: Why aren't maps safe for concurrent use, and what do you use instead?
Making every map operation thread-safe would slow down the common single-goroutine case, so the Go team chose not to. Concurrent reads are fine; a write concurrent with any other access is a data race. The runtime detects some of these cheaply and stops the program with fatal error: concurrent map writes (or concurrent map read and map write). That is a fatal error, not a panic, so recover can't catch it.
Choices: a struct holding a sync.Mutex (or RWMutex) and the map, which is right for most code; sync.Map, optimized for two cases (keys written once and read many times, or goroutines working on disjoint keys); or a sharded map (N maps, each with its own mutex, chosen by key hash) for heavy write contention.
package main
import (
"fmt"
"sync"
)
func main() {
var m sync.Map
var wg sync.WaitGroup
for i := range 100 {
wg.Go(func() { m.Store(i%10, i) })
}
wg.Wait()
n := 0
m.Range(func(_, _ any) bool { n++; return true })
v, loaded := m.LoadOrStore("new", 1)
fmt.Println(n, v, loaded)
}
Output:
10 1 false
Common wrong answer: "Use sync.Map for all concurrent maps." It loses static types (any keys and values) and is slower than a mutex-guarded map for general read/write workloads.
Follow-up: Why "detects some"? The check is a cheap flag in the map header, not a full race detector. Run tests with -race to find the races that don't happen to trip it.
Leaks, Races and Patterns
Q: What is a goroutine leak, and how do you find one?
A goroutine leaks when it blocks forever, typically on a send nobody receives, a receive from a channel nobody closes, a lock nobody releases, or a loop that never checks ctx.Done(). Each one holds its stack and everything it references, so leaks show up as slowly growing memory and goroutine counts.
Finding them: watch runtime.NumGoroutine() or the /sched/goroutines metrics over time; take a goroutine profile (/debug/pprof/goroutine?debug=2) and look for thousands of goroutines parked on the same line; in tests, go.uber.org/goleak fails a test that leaves goroutines behind. Go 1.26 added an experimental goroutine leak profile (build with GOEXPERIMENT=goroutineleakprofile): the GC reports goroutines blocked on channels or locks that no running code can reach anymore, which are leaked by definition.
package main
import (
"fmt"
"runtime"
"time"
)
func fetch(i int) string { time.Sleep(time.Duration(i) * time.Millisecond); return fmt.Sprint(i) }
func firstLeaky(n int) string {
ch := make(chan string) // unbuffered
for i := range n {
go func() { ch <- fetch(i) }() // the losers block on send forever
}
return <-ch
}
func firstFixed(n int) string {
ch := make(chan string, n) // room for every sender: nobody blocks
for i := range n {
go func() { ch <- fetch(i) }()
}
return <-ch
}
func main() {
before := runtime.NumGoroutine()
firstLeaky(10)
time.Sleep(50 * time.Millisecond)
fmt.Println("leaked:", runtime.NumGoroutine()-before)
before = runtime.NumGoroutine()
firstFixed(10)
time.Sleep(50 * time.Millisecond)
fmt.Println("leaked:", runtime.NumGoroutine()-before)
}
Output:
leaked: 9
leaked: 0
A context is the more general fix: each sender does select { case ch <- v: case <-ctx.Done(): } and the caller cancels when it has its answer.
Common wrong answer: "The GC frees blocked goroutines." It never frees a goroutine; the 1.26 leak profile reports them but doesn't collect them.
Follow-up: What leaks in a time.Ticker? Before Go 1.23, a ticker that was never stopped kept running forever. Since Go 1.23, unreferenced tickers are collected, but defer t.Stop() is still the right habit.
Q: What does the race detector do, and what are its limits?
go test -race (or go run -race, go build -race) compiles in ThreadSanitizer instrumentation. At runtime it records every memory access along with the happens-before relations created by channels, mutexes, WaitGroups and atomics. When two goroutines access the same memory, at least one writes, and neither access happens before the other, it prints a WARNING: DATA RACE report with both stack traces and where each goroutine was created.
Its limits: it finds races only in code that actually runs during that execution, so it needs tests that exercise concurrency; it costs roughly 5 to 10 times more memory and 2 to 20 times more CPU; it needs cgo on most platforms; and it doesn't find deadlocks, leaks or logic races (two correctly locked operations that should have been one). There are no false positives: every report is a real race.
package main
import (
"fmt"
"sync"
)
func main() {
counter := 0
var wg sync.WaitGroup
for range 1000 {
wg.Go(func() { counter++ }) // DATA RACE: read-modify-write without a lock
}
wg.Wait()
fmt.Println(counter <= 1000) // may print fewer than 1000 increments' worth
}
Without -race this prints true and the counter is often, but not always, exactly 1000. Run with -race and the program reports the race and exits with status 66. The fix is a mutex or atomic.Int64.
Common wrong answer: "The test passed with -race, so the code is race-free." It is race-free on the paths and interleavings that ran.
Follow-up: Is a "benign" race on a bool flag OK? No. Under the Go memory model a racy program has no guarantees: the compiler may hoist the read out of a loop so it never sees the update. Use atomic.Bool.
Q: Show fan-out, fan-in and a semaphore.
Fan-out means several goroutines read from one channel to share work. Fan-in means merging several channels into one. A semaphore bounds how many goroutines do something at once; a buffered channel of empty structs is the simplest one (golang.org/x/sync/semaphore adds weighted acquisition with a context). The Go Concurrency page covers each pattern at length; Part 4 builds a full worker pool and pipeline with tests.
package main
import (
"fmt"
"slices"
"sync"
"sync/atomic"
"time"
)
func square(in <-chan int) <-chan int {
out := make(chan int)
go func() {
defer close(out)
for v := range in {
out <- v * v
}
}()
return out
}
func fanIn(chans ...<-chan int) <-chan int {
out := make(chan int)
var wg sync.WaitGroup
for _, c := range chans {
wg.Go(func() {
for v := range c {
out <- v
}
})
}
go func() { wg.Wait(); close(out) }() // close once every input is drained
return out
}
func main() {
src := make(chan int)
go func() {
defer close(src)
for i := 1; i <= 6; i++ {
src <- i
}
}()
var got []int
for v := range fanIn(square(src), square(src), square(src)) { // fan-out: 3 readers
got = append(got, v)
}
slices.Sort(got)
fmt.Println(got)
sem := make(chan struct{}, 2) // at most 2 at a time
var running, peak atomic.Int32
var wg sync.WaitGroup
for range 8 {
wg.Go(func() {
sem <- struct{}{}
defer func() { <-sem }()
n := running.Add(1)
for p := peak.Load(); n > p && !peak.CompareAndSwap(p, n); p = peak.Load() {
}
time.Sleep(5 * time.Millisecond)
running.Add(-1)
})
}
wg.Wait()
fmt.Println("peak concurrency:", peak.Load())
}
Output:
peak concurrency: 2
Common wrong answer: Closing the merged output channel inside each forwarding goroutine. The first one to finish closes it, and the others panic with send on closed channel.
Follow-up: Results arrive out of order. How do you keep input order? Send (index, value) pairs and write into a pre-sized slice, or give each job its own result channel and read them in order.
Second follow-up: Channel or mutex? Channels for handing over ownership and coordinating (jobs, results, done signals). Mutexes for protecting shared state (a cache, a counter). If you are building a goroutine whose only job is to guard a map behind request and reply channels, a mutex is shorter and faster.
Testing
Q: How do you write table-driven tests with subtests and t.Parallel?
A table test is a slice of cases, each with a name, inputs and expected output, run in a loop with t.Run. Each t.Run creates a subtest: it gets its own name (TestSplit/empty), can be run alone with -run 'TestSplit/empty', and a failure in one doesn't stop the others. Calling t.Parallel() inside a subtest lets subtests run concurrently with each other. Since Go 1.22, the loop variable is per-iteration, so the old tc := tc line is no longer needed.
package textutil
import "strings"
// Fields splits s on commas and trims spaces, dropping empty fields.
func Fields(s string) []string {
var out []string
for f := range strings.SplitSeq(s, ",") {
if f = strings.TrimSpace(f); f != "" {
out = append(out, f)
}
}
return out
}
package textutil
import (
"slices"
"testing"
)
func TestFields(t *testing.T) {
tests := []struct {
name string
in string
want []string
}{
{"empty", "", nil},
{"one", "a", []string{"a"}},
{"spaces", " a , b ", []string{"a", "b"}},
{"blanks dropped", "a,,b,", []string{"a", "b"}},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
if got := Fields(tc.in); !slices.Equal(got, tc.want) {
t.Errorf("Fields(%q) = %q, want %q", tc.in, got, tc.want)
}
})
}
}
go test -v lists each subtest as --- PASS: TestFields/spaces. strings.SplitSeq (Go 1.24) is the iterator version of strings.Split, which avoids building the intermediate slice.
Common wrong answer: Using t.Fatal from a goroutine the test started. Fatal must be called from the test's own goroutine; use t.Error and return, or send the error back.
Follow-up: How do you clean up after a test? t.Cleanup(func(){...}) runs after the test and all its subtests finish, in LIFO order. t.TempDir() and t.Context() use it.
Q: How does fuzzing work in Go?
Go has built-in coverage-guided fuzzing (since 1.18). A fuzz test is a FuzzXxx(f *testing.F) function. You add seed inputs with f.Add, then call f.Fuzz with a function that takes those types and checks a property, something that must hold for every input, because the fuzzer doesn't know the expected output. Under plain go test, only the seeds (and any saved failures in testdata/fuzz/) run, so it doubles as a regression test. With go test -fuzz=FuzzReverse, the engine mutates inputs, keeps those that reach new code, and saves any failing input to testdata/fuzz/FuzzReverse/ so it reruns forever.
package reverse
import "unicode/utf8"
// Reverse reverses s rune by rune. Invalid UTF-8 is returned unchanged.
func Reverse(s string) string {
if !utf8.ValidString(s) {
return s
}
r := []rune(s)
for i, j := 0, len(r)-1; i < j; i, j = i+1, j-1 {
r[i], r[j] = r[j], r[i]
}
return string(r)
}
package reverse
import (
"testing"
"unicode/utf8"
)
func FuzzReverse(f *testing.F) {
for _, seed := range []string{"", "a", "hello", "世界"} {
f.Add(seed)
}
f.Fuzz(func(t *testing.T, s string) {
rev := Reverse(s)
if Reverse(rev) != s {
t.Errorf("double reverse of %q gave %q", s, Reverse(rev))
}
if utf8.ValidString(s) && !utf8.ValidString(rev) {
t.Errorf("Reverse(%q) produced invalid UTF-8 %q", s, rev)
}
})
}
Swap in a byte-by-byte Reverse and the 世界 seed already fails under plain go test. Remove that seed, and go test -fuzz=FuzzReverse found the bug in under a second when this page was written, minimizing it to Reverse("Ú") produced invalid UTF-8 "\x9a\xc3". Finding the input you didn't think of is what fuzzing is for. For the general idea of testing properties, see Property-Based Testing.
Common wrong answer: "Fuzzing runs on every go test." Only the seed corpus does. Active fuzzing needs -fuzz and runs until it fails or hits -fuzztime.
Follow-up: Which argument types are supported? string, []byte, the integer and float types, bool and rune/byte. Structs aren't; decode them from a []byte.
Q: How do you test code that uses time and goroutines? What is testing/synctest?
Tests that time.Sleep to wait for goroutines are slow and flaky. testing/synctest (experimental in Go 1.24, stable in Go 1.25) runs a function in an isolated bubble. Inside it, time is fake: the clock only advances when every goroutine in the bubble is blocked, and then it jumps straight to the next timer. So a test of a 5-second timeout finishes instantly and exactly. synctest.Wait() blocks until every other goroutine in the bubble is durably blocked, which replaces "sleep a bit and hope the goroutine got there".
package cache
import (
"sync"
"time"
)
// TTLCache drops entries after ttl.
type TTLCache struct {
mu sync.Mutex
ttl time.Duration
m map[string]string
}
func NewTTLCache(ttl time.Duration) *TTLCache {
return &TTLCache{ttl: ttl, m: map[string]string{}}
}
func (c *TTLCache) Set(k, v string) {
c.mu.Lock()
c.m[k] = v
c.mu.Unlock()
time.AfterFunc(c.ttl, func() {
c.mu.Lock()
delete(c.m, k)
c.mu.Unlock()
})
}
func (c *TTLCache) Get(k string) (string, bool) {
c.mu.Lock()
defer c.mu.Unlock()
v, ok := c.m[k]
return v, ok
}
package cache
import (
"testing"
"testing/synctest"
"time"
)
func TestTTLCacheExpires(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
c := NewTTLCache(time.Hour)
c.Set("k", "v")
time.Sleep(time.Hour - time.Nanosecond) // fake time: returns instantly
synctest.Wait()
if _, ok := c.Get("k"); !ok {
t.Fatal("expired too early")
}
time.Sleep(time.Nanosecond)
synctest.Wait() // let the AfterFunc goroutine finish deleting
if _, ok := c.Get("k"); ok {
t.Fatal("did not expire")
}
})
}
This test covers an hour of behavior and runs in milliseconds.
Common wrong answer: "Inject a fake clock interface everywhere." That was the standard approach and it still works, but synctest tests the real time calls without changing production code.
Follow-up: What doesn't count as "durably blocked"? Blocking on I/O (a real network socket) or on something outside the bubble. Use in-memory fakes like net.Pipe inside the bubble.
Q: How do you write a benchmark in modern Go?
Benchmarks are BenchmarkXxx(b *testing.B) functions run with go test -bench=. -benchmem. Since Go 1.24, write the loop as for b.Loop() { ... } instead of for i := 0; i < b.N; i++. b.Loop runs setup before the loop only once, times only the loop, and keeps the compiler from optimizing away the body's results, a classic source of "0.3 ns/op" fake numbers. Go 1.26 removed its last drawback: the loop body can now be inlined like normal code. Use b.ReportAllocs() (or -benchmem) to see allocations, and compare runs with benchstat, not by eyeballing one run.
package concat
import "strings"
func Plus(parts []string) string {
s := ""
for _, p := range parts {
s += p // copies the whole string every time
}
return s
}
func Builder(parts []string) string {
n := 0
for _, p := range parts {
n += len(p)
}
var sb strings.Builder
sb.Grow(n) // one allocation
for _, p := range parts {
sb.WriteString(p)
}
return sb.String()
}
package concat
import (
"strings"
"testing"
)
var parts = strings.Split(strings.Repeat("word,", 100), ",")
func TestSame(t *testing.T) {
if Plus(parts) != Builder(parts) {
t.Fatal("results differ")
}
}
func BenchmarkPlus(b *testing.B) {
b.ReportAllocs()
for b.Loop() {
Plus(parts)
}
}
func BenchmarkBuilder(b *testing.B) {
b.ReportAllocs()
for b.Loop() {
Builder(parts)
}
}
One run of go test -bench=. -benchmem on the machine used for this page (Go 1.26.1, windows/amd64, 32 threads) gave:
BenchmarkPlus-32 231802 5661 ns/op 21080 B/op 99 allocs/op
BenchmarkBuilder-32 4149954 279.7 ns/op 416 B/op 1 allocs/op
Your numbers will differ; the ratio (one allocation versus one per part) is the point.
Common wrong answer: Benchmarking on a laptop on battery, once, and reporting a 5% win. Run -count=10 and use benchstat to see whether the difference is statistically real.
Follow-up: How do you benchmark several input sizes? Use b.Run(fmt.Sprintf("n=%d", n), ...) sub-benchmarks inside a loop over sizes.
Part 3: Staff
The Memory Model
Q: What is the Go memory model, and what does "happens before" mean?
The memory model says when a read in one goroutine is guaranteed to see a write from another. Within a goroutine, things happen in program order. Across goroutines, a write is guaranteed visible to a read only if the write happens before the read, and the only ways to create that ordering are synchronization operations:
- A send on a channel happens before the matching receive completes. Closing a channel happens before a receive that returns because it is closed.
- For an unbuffered channel, the receive happens before the send completes. For a channel with capacity C, the k-th receive happens before the (k+C)-th send completes, which is why a buffered channel works as a semaphore.
Unlockhappens before the nextLockreturns.Once's function returns before anyDoreturns.wg.Donehappens before theWaitit unblocks.- Atomics (since the 2022 revision of the model): if an atomic load observes an atomic store, the store happens before the load. Go atomics are sequentially consistent.
- The
gostatement happens before the new goroutine starts. A goroutine's exit is not synchronized with anything.
A program without data races behaves as if it were sequentially consistent ("DRF-SC"). A program with a race has almost no guarantees: the compiler may keep a value in a register so a loop never sees an update, and a racy read of a multi-word value (an interface, a string, a slice) can see half of one write and half of another, which can crash the program.
package main
import (
"fmt"
"runtime"
"sync/atomic"
)
var data []string
var ready atomic.Bool
func main() {
go func() {
data = append(data, "hello") // plain write...
ready.Store(true) // ...published by an atomic store
}()
for !ready.Load() { // the load that observes true synchronizes with the store
runtime.Gosched()
}
fmt.Println(data[0]) // guaranteed to see "hello"
}
Output:
hello
Replace ready with a plain bool and the program has a data race: -race reports it, and the compiler is allowed to turn the loop into an infinite one.
Common wrong answer: "On x86, writes are visible in order anyway, so plain variables are fine." The compiler reorders and caches too, not just the CPU, and the code must also run on ARM.
Follow-up: Does time.Sleep create happens-before? No. Sleeping makes the race less likely to show up, which is worse than useless.
Memory and the Runtime
Q: What is escape analysis, and how do you see its decisions?
The compiler decides whether each value can live on the goroutine's stack (freed automatically when the function returns, no GC cost) or must go to the heap (managed by the garbage collector). A value escapes to the heap when the compiler can't prove it isn't used after the function returns: its address is returned or stored somewhere long-lived, it is captured by a closure that outlives the call, it is put in an interface passed to code the compiler can't see through, or it is too big or its size isn't known at compile time. Escape analysis is conservative: when unsure, it picks the heap.
go build -gcflags=-m prints the decisions (-m=2 explains why).
package main
import "fmt"
type point struct{ x, y int }
func onStack() int {
p := point{1, 2} // never leaves the function
return p.x + p.y
}
func toHeap() *point {
p := point{3, 4}
return &p // outlives the call
}
func boxed(n int) {
fmt.Println(n) // n is copied into an interface argument
}
func sized() int {
buf := make([]byte, 64) // constant size, doesn't escape
return len(buf)
}
func dynamic(n int) []byte {
return make([]byte, n) // returned: escapes
}
func main() {
fmt.Println(onStack(), toHeap().x, sized(), len(dynamic(10)))
boxed(5)
}
go build -gcflags=-m . printed, among the inlining notes (can inline onStack, ...):
./main.go:13:2: moved to heap: p
./main.go:18:14: n escapes to heap
./main.go:22:13: make([]byte, 64) does not escape
./main.go:27:13: make([]byte, n) escapes to heap
Note that &p doesn't mean "heap" by itself: Go has no new versus stack distinction for you to pick. Taking an address is free if the pointer doesn't outlive the frame. And inlining changes the answer: the same run also printed make([]byte, 10) does not escape for the copy of dynamic inlined into main, because there the slice doesn't outlive the frame.
Common wrong answer: "Pointers always mean heap allocation." Escape is about lifetime, not syntax.
Follow-up: How do you keep a hot value off the heap? Return values instead of pointers for small structs, let the caller pass in a buffer (func Read(p []byte) style), avoid interfaces in the hot path, and check with -gcflags=-m after each change.
Q: How do goroutine stacks work? Can a goroutine overflow its stack?
Each goroutine starts with a small stack (2 KB minimum; since Go 1.19 the runtime picks the starting size from the average stack use it has seen). Every function's prologue checks whether there is enough room. If not, the runtime allocates a stack twice as big, copies the old one over and fixes up pointers into it, then continues. Stacks shrink again during GC when mostly unused. Because stacks move, Go doesn't let you keep raw pointers into them across calls without the runtime knowing (one reason cgo has strict pointer rules).
The maximum is 1 GB on 64-bit systems by default (debug.SetMaxStack changes it). Exceeding it is a fatal error, goroutine stack exceeds 1000000000-byte limit, which recover can't catch, so runaway recursion kills the process.
package main
import "fmt"
func depth(n int) int {
if n == 0 {
return 0
}
var pad [64]byte // make each frame bigger
pad[n%64] = 1
return int(pad[n%64]) + depth(n-1)
}
func main() {
fmt.Println(depth(1_000_000)) // about 100 MB of stack, grown on demand
}
Output:
1000000
A C program with an 8 MB thread stack would crash on this; Go just grows the stack.
Common wrong answer: "Goroutines are cheap because they share one stack." Each has its own; they are cheap because it starts small and grows.
Follow-up: Why might a function with a big local array be slow on first call? The stack check fails, so the runtime grows and copies the stack. Hot paths that run on fresh goroutines can see this in profiles as runtime.morestack.
Q: How does Go's garbage collector work, and what do GOGC and GOMEMLIMIT control?
Go uses a concurrent, non-moving, non-generational mark-and-sweep collector. Marking runs alongside your goroutines, using a write barrier to track pointer changes made during the mark phase; stop-the-world pauses are short (typically well under a millisecond) and only bracket the phases. Goroutines that allocate during marking are drafted into "mark assist" work, which is how GC cost shows up as latency in allocation-heavy code. Go 1.26 made the Green Tea collector the default: it scans small objects page by page for better memory locality, and the release notes report 10 to 40% less GC overhead in GC-heavy programs.
The knobs:
GOGC(default 100) sets the heap growth target: the next GC starts when the heap reaches live heap × (1 + GOGC/100). With 100 MB live, the next cycle starts around 200 MB. Higher means fewer GCs and more memory;GOGC=offdisables GC.GOMEMLIMIT(Go 1.19) is a soft memory limit for the whole Go runtime. Near the limit, the GC runs more often regardless ofGOGC. Set it to roughly 90% of a container's memory limit to avoid OOM kills, and combine with a highGOGCto save CPU when there's headroom. If live memory really exceeds the limit, the GC caps its own CPU use (around 50%) rather than thrash, and the process may still be OOM-killed.
package main
import (
"fmt"
"math"
"runtime"
"runtime/debug"
)
var sink [][]byte
func main() {
fmt.Println("default GOGC:", debug.SetGCPercent(200)) // returns the previous value
prev := debug.SetMemoryLimit(512 << 20) // 512 MiB soft limit
fmt.Println("no limit before:", prev == math.MaxInt64)
for range 200 {
sink = append(sink, make([]byte, 1<<20))
if len(sink) > 10 {
sink = sink[1:] // keep ~10 MiB live, churn the rest
}
}
var ms runtime.MemStats
runtime.ReadMemStats(&ms)
fmt.Println("GC ran:", ms.NumGC > 0)
}
Output (when the GOGC environment variable is unset):
default GOGC: 100
no limit before: true
GC ran: true
Common wrong answer: "GOMEMLIMIT is a hard cap like a cgroup limit." It's a target the GC works towards; allocation never fails because of it.
Follow-up: How do you see what the GC is doing? GODEBUG=gctrace=1 prints one line per cycle (heap sizes, CPU time, pause times). In production, export runtime/metrics (for example /gc/cycles/total:gc-cycles) to your metrics system.
Q: How do you find out why a Go service is slow or using too much memory?
Measure with pprof before changing anything:
- CPU profile: where time goes.
go test -cpuprofile, or/debug/pprof/profile?seconds=30fromnet/http/pprof. - Heap profile:
inuse_spaceshows what is live now (leaks, big caches);alloc_spaceshows what has been allocated since start (GC pressure). - Goroutine profile: what every goroutine is blocked on (leaks, deadlocks).
- Block and mutex profiles: where goroutines wait on channels or locks. Off by default; enable with
runtime.SetBlockProfileRateandruntime.SetMutexProfileFraction. - Execution trace (
go tool trace): scheduler latency, GC pauses, what each P was doing over time. Since Go 1.25,trace.FlightRecorderkeeps the last few seconds in memory so you can save a trace after something went wrong.
Open any profile with go tool pprof -http=:8080 cpu.pprof; in Go 1.26 the web UI opens on the flame graph. Go Profiling covers the workflow end to end, and Continuous Profiling covers running it all the time in production.
package main
import (
"fmt"
"os"
"runtime/pprof"
"strings"
)
func work() int {
n := 0
for i := range 2_000_000 {
n += len(strings.Repeat("x", i%16))
}
return n
}
func main() {
f, err := os.CreateTemp("", "cpu-*.pprof")
if err != nil {
panic(err)
}
defer os.Remove(f.Name())
if err := pprof.StartCPUProfile(f); err != nil {
panic(err)
}
fmt.Println(work())
pprof.StopCPUProfile()
f.Close()
info, _ := os.Stat(f.Name())
fmt.Println("profile written:", info.Size() > 0)
}
Output:
15000000
profile written: true
Then go tool pprof -top <file> lists the hottest functions, here strings.Repeat and the allocator.
Common wrong answer: Optimizing what looks slow. Profiles regularly show the cost is somewhere else: JSON encoding, logging, a lock.
Follow-up: What is PGO? Profile-guided optimization (stable since Go 1.21): put a CPU profile from production at default.pgo in the main package, and the compiler inlines and devirtualizes the hot paths more aggressively. Typical gains are a few percent of CPU.
Q: How do you reduce allocations in a hot path?
Every heap allocation costs allocator time now and GC time later. The usual tools, in the order to try them:
- Preallocate slices and maps when you know the size:
make([]T, 0, n),make(map[K]V, n). - Build strings with
strings.Builder(andGrowit), not+in a loop.Builder.String()returns the bytes without copying. - Append into reusable buffers:
strconv.AppendInt,fmt.Appendf,time.AppendFormatwrite into a[]byteyou own instead of returning new strings. - Avoid interface boxing in hot code (
fmt.Sprintf("%d", n)boxesnand allocates the result). - Pool large short-lived objects with
sync.Pool. The pool is cleared gradually across GC cycles, so it's a cache, not a free list; alwaysResetwhat you get, and don't pool objects whose size varies wildly (one huge buffer stays in the pool).
package main
import (
"bytes"
"fmt"
"strconv"
"sync"
"testing"
)
var bufPool = sync.Pool{New: func() any { return new(bytes.Buffer) }}
func main() {
n := 12345
fmt.Println("Sprintf:", testing.AllocsPerRun(1000, func() {
_ = fmt.Sprintf("id=%d", n)
}))
buf := make([]byte, 0, 32)
fmt.Println("AppendInt:", testing.AllocsPerRun(1000, func() {
buf = append(buf[:0], "id="...)
buf = strconv.AppendInt(buf, int64(n), 10)
}))
fmt.Println("pooled buffer:", testing.AllocsPerRun(1000, func() {
b := bufPool.Get().(*bytes.Buffer)
b.Reset()
b.WriteString("id=")
b.Write(strconv.AppendInt(b.AvailableBuffer(), int64(n), 10)) // no temporary string
bufPool.Put(b)
}))
}
Output:
Sprintf: 1
AppendInt: 0
pooled buffer: 0
Sprintf costs one allocation for the result string. The other two reuse memory. A first version of the pooled case used b.WriteString(strconv.Itoa(n)) and measured 1 allocation: Itoa built a temporary string. AvailableBuffer plus AppendInt writes the digits straight into the buffer's spare capacity.
Common wrong answer: Reaching for sync.Pool first. It adds complexity and helps only for objects that are both large and frequently allocated; preallocation and avoiding conversions are usually enough.
Follow-up: What does testing.AllocsPerRun measure? The average number of heap allocations per call. A test that asserts == 0 guards a hot path against regressions.
Modules and Tooling
Q: How do modules and workspaces work?
A module is a tree of packages with a go.mod at its root that declares the module path, the go language version, and its requirements. go.sum stores cryptographic hashes of every dependency version, checked against the public checksum database. Go resolves versions with minimal version selection (MVS): for each dependency it uses the highest of the minimum versions that anything requires, never "latest". Builds are reproducible without a lock file, and an upgrade only happens when someone asks for it.
Other rules worth knowing: major versions 2 and up change the import path (example.com/lib/v2), so v1 and v2 can coexist; replace points a dependency at a fork or a local directory but only applies in the main module; the toolchain line (Go 1.21) lets go download the toolchain a module needs; since Go 1.24, tool lines in go.mod track developer tools (go get -tool, then go tool name).
A workspace (go.work, Go 1.18) builds several local modules together without editing their go.mod files, which is ideal for changing a library and its consumer at once. Don't commit go.work for a published library.
go mod init example.com/app # Go 1.26 writes "go 1.25.0" by default
go get golang.org/x/sync@latest # add or upgrade a dependency
go mod tidy # add missing, drop unused requirements
go get -tool golang.org/x/tools/cmd/stringer # Go 1.24+: record a tool in go.mod
go tool stringer -type=Color # run it at the recorded version
go work init ./app ./lib # build app against the local lib
go work use ./other
go list -m all # the versions MVS selected
go mod why -m golang.org/x/text # why is this in my build?
Common wrong answer: "go get picks the newest version of every transitive dependency." MVS picks the minimum that satisfies everyone; go get -u is the explicit "upgrade" button.
Follow-up: Why does go mod init in Go 1.26 write go 1.25.0? So new modules are usable by people still on the previous release by default. You can raise it with go get go@1.26.
Q: Which tools belong in every Go project's CI?
go vet ./...: the analyzers built into Go. They catch real bugs:printfformat mismatches,copylocks,loopclosure, unreachable code,waitgroupandhostport(both new in 1.25).go testalready runs a subset.go test -race ./...: the race detector on every test run in CI.govulncheck ./...(golang.org/x/vuln/cmd/govulncheck): checks dependencies against the Go vulnerability database and looks at your call graph, so it reports only vulnerabilities in functions you actually call.staticcheckorgolangci-lint: a much larger set of checks (unused code, deprecated APIs, common mistakes).go fix ./...: rewritten in Go 1.26 as the home of "modernizers" that update code to current idioms (for example, removingx := xloop copies or switching tomin/maxandsliceshelpers), plus//go:fix inlinedirectives that let library authors migrate callers automatically.gofmt -l .should print nothing.
gofmt -l .
go vet ./...
go test -race -count=1 ./...
go run golang.org/x/vuln/cmd/govulncheck@latest ./...
go fix -diff ./... # review modernizer suggestions before applying
Common wrong answer: "go vet is a style linter." It only reports likely bugs, with few false positives, which is why go test runs part of it by default.
Follow-up: How do you pin linters to a version? With tool lines in go.mod (Go 1.24+), so everyone and CI run the same version through go tool.
Part 4: Write It From Scratch
Interviewers grade these on shutdown, cancellation and races, not on the happy path. Each build below is a package plus a test file; save both in one directory with a go.mod and run go test -race ./.... The tests use testing/synctest where time is involved, so they run instantly and deterministically.
Q: Build a bounded worker pool with context cancellation
Level: senior. Process jobs with at most n goroutines, return results in input order, stop early on the first error or when the caller cancels.
package workerpool
import (
"context"
"sync"
)
// Run applies fn to every job using n workers. It returns results in input order,
// or the first error (a job's error, or the cause of ctx's cancellation).
func Run[J, R any](ctx context.Context, n int, jobs []J,
fn func(context.Context, J) (R, error)) ([]R, error) {
ctx, cancel := context.WithCancelCause(ctx)
defer cancel(nil)
results := make([]R, len(jobs))
next := make(chan int) // job indexes
var wg sync.WaitGroup
for range n {
wg.Go(func() {
for i := range next {
r, err := fn(ctx, jobs[i])
if err != nil {
cancel(err) // first cause wins; later calls are no-ops
return
}
results[i] = r // each index is written by exactly one worker
}
})
}
feed:
for i := range jobs {
select {
case next <- i:
case <-ctx.Done():
break feed // stop handing out work
}
}
close(next)
wg.Wait()
if err := context.Cause(ctx); err != nil {
return nil, err
}
return results, nil
}
package workerpool
import (
"context"
"errors"
"sync/atomic"
"testing"
"testing/synctest"
"time"
)
func TestOrderAndBound(t *testing.T) {
var running, peak atomic.Int32
double := func(ctx context.Context, x int) (int, error) {
n := running.Add(1)
defer running.Add(-1)
for p := peak.Load(); n > p && !peak.CompareAndSwap(p, n); p = peak.Load() {
}
time.Sleep(time.Millisecond)
return x * 2, nil
}
got, err := Run(context.Background(), 3, []int{1, 2, 3, 4, 5, 6, 7}, double)
if err != nil || len(got) != 7 || got[0] != 2 || got[6] != 14 {
t.Fatalf("got %v, %v", got, err)
}
if peak.Load() > 3 {
t.Fatalf("peak concurrency %d > 3", peak.Load())
}
}
func TestFirstErrorStopsWork(t *testing.T) {
boom := errors.New("boom")
var calls atomic.Int32
_, err := Run(context.Background(), 2, make([]int, 1000), func(ctx context.Context, _ int) (int, error) {
if calls.Add(1) == 5 {
return 0, boom
}
return 0, nil
})
if !errors.Is(err, boom) {
t.Fatalf("err = %v", err)
}
if calls.Load() > 10 {
t.Fatalf("%d calls: work did not stop", calls.Load())
}
}
func TestCallerCancels(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
ctx, cancel := context.WithTimeout(t.Context(), 50*time.Millisecond)
defer cancel()
_, err := Run(ctx, 4, make([]int, 100), func(ctx context.Context, _ int) (int, error) {
select {
case <-time.After(time.Second):
return 0, nil
case <-ctx.Done():
return 0, ctx.Err()
}
})
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("err = %v", err)
}
})
}
Common wrong answer: Starting one goroutine per job (unbounded), or a feeder that blocks forever on next <- i after every worker has exited because of an error. The select on ctx.Done() in the feeder is what prevents that.
Follow-up: How would you stream results instead of collecting them? Return a <-chan Result that the pool closes after wg.Wait(), and document that the caller must drain it or cancel.
Q: Build a token-bucket rate limiter
Level: senior. A bucket holds up to burst tokens and refills at rate tokens per second. Allow takes a token if one is available; Wait blocks until it can take one or the context ends. Instead of a background goroutine refilling the bucket, compute the refill lazily from the elapsed time on each call. The design is covered in depth in Rate Limiter (LLD).
package ratelimit
import (
"context"
"sync"
"time"
)
type Bucket struct {
mu sync.Mutex
rate float64 // tokens per second
burst float64
tokens float64
last time.Time
}
func New(rate float64, burst int) *Bucket {
return &Bucket{rate: rate, burst: float64(burst), tokens: float64(burst), last: time.Now()}
}
func (b *Bucket) refill(now time.Time) {
b.tokens = min(b.burst, b.tokens+now.Sub(b.last).Seconds()*b.rate)
b.last = now
}
// reserve takes a token if possible; otherwise it reports how long until one is available.
func (b *Bucket) reserve() (ok bool, wait time.Duration) {
b.mu.Lock()
defer b.mu.Unlock()
b.refill(time.Now())
if b.tokens >= 1 {
b.tokens--
return true, 0
}
return false, time.Duration((1 - b.tokens) / b.rate * float64(time.Second))
}
func (b *Bucket) Allow() bool {
ok, _ := b.reserve()
return ok
}
func (b *Bucket) Wait(ctx context.Context) error {
for {
ok, wait := b.reserve()
if ok {
return nil
}
t := time.NewTimer(max(wait, time.Nanosecond))
select {
case <-t.C:
case <-ctx.Done():
t.Stop()
return ctx.Err()
}
}
}
package ratelimit
import (
"context"
"errors"
"testing"
"testing/synctest"
"time"
)
func TestBurstThenRefill(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
b := New(2, 3) // 2 tokens/s, burst 3
for i := range 3 {
if !b.Allow() {
t.Fatalf("call %d denied inside the burst", i)
}
}
if b.Allow() {
t.Fatal("4th call allowed: bucket should be empty")
}
time.Sleep(time.Second) // fake clock: +2 tokens
if !b.Allow() || !b.Allow() || b.Allow() {
t.Fatal("expected exactly 2 tokens after 1s")
}
})
}
func TestWaitPacesCalls(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
b := New(10, 1) // one token every 100ms
start := time.Now()
for range 5 {
if err := b.Wait(t.Context()); err != nil {
t.Fatal(err)
}
}
if got := time.Since(start); got < 400*time.Millisecond || got > 401*time.Millisecond {
t.Fatalf("5 calls took %v, want ~400ms", got)
}
})
}
func TestWaitHonoursContext(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
b := New(0.1, 1) // one token every 10s
b.Allow()
ctx, cancel := context.WithTimeout(t.Context(), time.Second)
defer cancel()
if err := b.Wait(ctx); !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("err = %v", err)
}
})
}
Common wrong answer: A goroutine with a time.Ticker that adds a token every tick. It burns a goroutine per limiter, leaks if nobody stops it, and its precision is bounded by the tick.
Follow-up: Would you write this in production? No: golang.org/x/time/rate implements the same model with reservations and dynamic limits. For limits shared across instances you need Redis or similar; see Distributed Rate Limiting.
Q: Build an in-process pub-sub with channels
Level: senior. Subscribers get a buffered channel per topic. A slow subscriber must not block the publisher or the other subscribers, so delivery is non-blocking: a full buffer drops the message and the drop is counted. Unsubscribing closes the subscriber's channel exactly once.
package pubsub
import "sync"
type Broker[T any] struct {
mu sync.RWMutex
subs map[string]map[chan T]struct{}
closed bool
}
func New[T any]() *Broker[T] { return &Broker[T]{subs: map[string]map[chan T]struct{}{}} }
// Subscribe returns a channel of messages for topic and a function that unsubscribes.
func (b *Broker[T]) Subscribe(topic string, buffer int) (<-chan T, func()) {
ch := make(chan T, buffer)
b.mu.Lock()
defer b.mu.Unlock()
if b.closed {
close(ch)
return ch, func() {}
}
if b.subs[topic] == nil {
b.subs[topic] = map[chan T]struct{}{}
}
b.subs[topic][ch] = struct{}{}
var once sync.Once
return ch, func() {
once.Do(func() {
b.mu.Lock()
defer b.mu.Unlock()
if _, ok := b.subs[topic][ch]; ok { // Close may have closed it already
delete(b.subs[topic], ch)
close(ch)
}
})
}
}
// Publish delivers msg to every subscriber of topic without blocking.
// It returns how many subscribers missed the message because their buffer was full.
func (b *Broker[T]) Publish(topic string, msg T) (dropped int) {
b.mu.RLock() // channels are only closed under the write lock, so sending here is safe
defer b.mu.RUnlock()
for ch := range b.subs[topic] {
select {
case ch <- msg:
default:
dropped++
}
}
return dropped
}
// Close unsubscribes everyone. Later Publish calls deliver nothing.
func (b *Broker[T]) Close() {
b.mu.Lock()
defer b.mu.Unlock()
b.closed = true
for _, set := range b.subs {
for ch := range set {
close(ch)
}
}
clear(b.subs)
}
package pubsub
import (
"sync"
"testing"
)
func TestFanOutAndDrops(t *testing.T) {
b := New[string]()
fast, _ := b.Subscribe("news", 10)
slow, _ := b.Subscribe("news", 1)
other, _ := b.Subscribe("sport", 10)
if d := b.Publish("news", "a"); d != 0 {
t.Fatalf("dropped %d", d)
}
if d := b.Publish("news", "b"); d != 1 { // slow's buffer is full
t.Fatalf("dropped %d, want 1", d)
}
if <-fast != "a" || <-fast != "b" || <-slow != "a" {
t.Fatal("wrong delivery")
}
if len(other) != 0 {
t.Fatal("message leaked to another topic")
}
}
func TestUnsubscribeAndCloseAreSafe(t *testing.T) {
b := New[int]()
ch, unsub := b.Subscribe("t", 1)
unsub()
unsub() // idempotent
if _, ok := <-ch; ok {
t.Fatal("channel should be closed")
}
var wg sync.WaitGroup
for i := range 50 {
_, u := b.Subscribe("t", 1)
wg.Go(func() { b.Publish("t", i) })
wg.Go(u)
}
wg.Go(b.Close)
wg.Wait()
b.Publish("t", 1) // after Close: no panic
}
Common wrong answer: Blocking sends (ch <- msg) in Publish, so one stuck consumer freezes every publisher; or closing subscriber channels without holding the lock that Publish holds, which gives send on closed channel.
Follow-up: What if messages must not be dropped? Then you need backpressure (block the publisher, with a context timeout) or a per-subscriber unbounded queue drained by its own goroutine, plus monitoring of queue depth. See the design trade-offs in Pub-Sub (LLD).
Q: Build a context-aware retry with exponential backoff
Level: senior. Retry a call with exponential backoff and jitter, give up after N attempts, never sleep past the caller's deadline, and don't retry errors marked permanent. Jitter spreads retries out so that a thousand clients that failed together don't retry together. Retry Strategies discusses the policy choices.
package retry
import (
"context"
"errors"
"fmt"
"math/rand/v2"
"time"
)
type Policy struct {
Attempts int
Base, Max time.Duration
}
type permanent struct{ err error }
func (p permanent) Error() string { return p.err.Error() }
func (p permanent) Unwrap() error { return p.err }
// Permanent marks err as not worth retrying.
func Permanent(err error) error { return permanent{err} }
func Do(ctx context.Context, p Policy, fn func(context.Context) error) error {
var err error
for attempt := range p.Attempts {
if err = fn(ctx); err == nil {
return nil
}
if _, ok := errors.AsType[permanent](err); ok {
return err
}
if attempt == p.Attempts-1 {
break
}
d := min(p.Max, p.Base<<attempt)
d = d/2 + rand.N(d/2+1) // "equal jitter": between d/2 and d
t := time.NewTimer(d)
select {
case <-t.C:
case <-ctx.Done():
t.Stop()
return errors.Join(err, context.Cause(ctx))
}
}
return fmt.Errorf("after %d attempts: %w", p.Attempts, err)
}
package retry
import (
"context"
"errors"
"testing"
"testing/synctest"
"time"
)
var errFlaky = errors.New("flaky")
func TestSucceedsAfterRetries(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
calls := 0
err := Do(t.Context(), Policy{Attempts: 5, Base: 100 * time.Millisecond, Max: time.Second},
func(context.Context) error {
if calls++; calls < 3 {
return errFlaky
}
return nil
})
if err != nil || calls != 3 {
t.Fatalf("err=%v calls=%d", err, calls)
}
})
}
func TestGivesUpAndWraps(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
start := time.Now()
err := Do(t.Context(), Policy{Attempts: 4, Base: 100 * time.Millisecond, Max: 150 * time.Millisecond},
func(context.Context) error { return errFlaky })
if !errors.Is(err, errFlaky) {
t.Fatalf("err = %v", err)
}
// three waits: jittered 100ms, then capped 150ms twice -> between 200ms and 400ms
if el := time.Since(start); el < 200*time.Millisecond || el > 400*time.Millisecond {
t.Fatalf("elapsed %v", el)
}
})
}
func TestPermanentAndDeadline(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
calls := 0
err := Do(t.Context(), Policy{Attempts: 5, Base: time.Millisecond, Max: time.Second},
func(context.Context) error { calls++; return Permanent(errFlaky) })
if calls != 1 || !errors.Is(err, errFlaky) {
t.Fatalf("calls=%d err=%v", calls, err)
}
ctx, cancel := context.WithTimeout(t.Context(), 50*time.Millisecond)
defer cancel()
err = Do(ctx, Policy{Attempts: 5, Base: time.Second, Max: time.Second},
func(context.Context) error { return errFlaky })
if !errors.Is(err, context.DeadlineExceeded) || !errors.Is(err, errFlaky) {
t.Fatalf("err = %v", err)
}
})
}
Common wrong answer: time.Sleep(backoff) between attempts, which ignores cancellation, so a request that the client abandoned keeps retrying for its full budget.
Follow-up: What should never be retried? Non-idempotent operations without an idempotency key (a payment), and errors that won't change (400 Bad Request, permission denied). Retry 429 and 503, and honour a Retry-After header when there is one.
Q: Build a concurrency-safe LRU cache
Level: senior. Get and Put in O(1): a map from key to a node in a doubly linked list ordered by recency. container/list provides the list. One mutex guards both, because every Get also modifies the list (moving the node to the front), so an RWMutex buys nothing. LRU Cache (LLD) discusses the design and sharding.
package lru
import (
"container/list"
"sync"
)
type entry[K comparable, V any] struct {
key K
val V
}
type Cache[K comparable, V any] struct {
mu sync.Mutex
cap int
order *list.List // front = most recently used
items map[K]*list.Element
}
func New[K comparable, V any](capacity int) *Cache[K, V] {
if capacity < 1 {
panic("lru: capacity must be positive")
}
return &Cache[K, V]{cap: capacity, order: list.New(), items: make(map[K]*list.Element, capacity)}
}
func (c *Cache[K, V]) Get(k K) (V, bool) {
c.mu.Lock()
defer c.mu.Unlock()
if el, ok := c.items[k]; ok {
c.order.MoveToFront(el)
return el.Value.(*entry[K, V]).val, true
}
var zero V
return zero, false
}
func (c *Cache[K, V]) Put(k K, v V) {
c.mu.Lock()
defer c.mu.Unlock()
if el, ok := c.items[k]; ok {
el.Value.(*entry[K, V]).val = v
c.order.MoveToFront(el)
return
}
c.items[k] = c.order.PushFront(&entry[K, V]{k, v})
if c.order.Len() > c.cap {
oldest := c.order.Back()
c.order.Remove(oldest)
delete(c.items, oldest.Value.(*entry[K, V]).key)
}
}
func (c *Cache[K, V]) Len() int {
c.mu.Lock()
defer c.mu.Unlock()
return c.order.Len()
}
package lru
import (
"sync"
"testing"
)
func TestEviction(t *testing.T) {
c := New[string, int](2)
c.Put("a", 1)
c.Put("b", 2)
c.Get("a") // a is now most recent
c.Put("c", 3) // evicts b
if _, ok := c.Get("b"); ok {
t.Fatal("b should be evicted")
}
if v, ok := c.Get("a"); !ok || v != 1 {
t.Fatal("a should survive")
}
c.Put("a", 10) // update in place, no growth
if v, _ := c.Get("a"); v != 10 || c.Len() != 2 {
t.Fatalf("update failed: v=%d len=%d", v, c.Len())
}
}
func TestConcurrentUse(t *testing.T) {
c := New[int, int](64)
var wg sync.WaitGroup
for g := range 8 {
wg.Go(func() {
for i := range 1000 {
c.Put((g*1000+i)%100, i)
c.Get(i % 100)
}
})
}
wg.Wait()
if c.Len() != 64 {
t.Fatalf("len = %d", c.Len())
}
}
Common wrong answer: Using RWMutex and taking only RLock in Get, which then calls MoveToFront: a data race that -race reports on the first concurrent test.
Follow-up: How do you scale it across 64 cores? Shard: N independent caches selected by key hash, each with its own lock. You trade exact global LRU order for much less contention, which is what libraries like ristretto and otter do, with smarter admission policies.
Q: Build a singleflight-style deduplicator
Level: senior–staff. When 1,000 requests miss the cache for the same key at once, only one should hit the database; the rest wait for its result. This is golang.org/x/sync/singleflight. The tricky parts are the happens-before between the leader's write and the waiters' reads (a WaitGroup gives it), and what happens if the function panics (waiters must not hang forever).
package flight
import (
"errors"
"sync"
)
var ErrPanicked = errors.New("flight: function panicked")
type call[V any] struct {
wg sync.WaitGroup
val V
err error
dups int
}
type Group[K comparable, V any] struct {
mu sync.Mutex
m map[K]*call[V]
}
// Do runs fn once per key at a time. Concurrent callers with the same key wait and
// share the result. shared reports whether the result went to more than one caller.
func (g *Group[K, V]) Do(key K, fn func() (V, error)) (v V, err error, shared bool) {
g.mu.Lock()
if g.m == nil {
g.m = make(map[K]*call[V])
}
if c, ok := g.m[key]; ok {
c.dups++
g.mu.Unlock()
c.wg.Wait() // Done happens before Wait returns: c.val and c.err are visible
return c.val, c.err, true
}
c := &call[V]{err: ErrPanicked} // overwritten unless fn panics
c.wg.Add(1)
g.m[key] = c
g.mu.Unlock()
defer func() { // runs on return and on panic
g.mu.Lock()
delete(g.m, key)
shared = c.dups > 0
g.mu.Unlock()
c.wg.Done()
}()
c.val, c.err = fn()
return c.val, c.err, false
}
package flight
import (
"errors"
"sync"
"sync/atomic"
"testing"
"testing/synctest"
)
func TestDeduplicates(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
var g Group[string, int]
var calls, sharedCount atomic.Int32
release := make(chan struct{})
var wg sync.WaitGroup
for range 10 {
wg.Go(func() {
v, err, shared := g.Do("user:1", func() (int, error) {
calls.Add(1)
<-release // hold the call open until everyone has joined
return 42, nil
})
if v != 42 || err != nil {
t.Errorf("got %d, %v", v, err)
}
if shared {
sharedCount.Add(1)
}
})
}
synctest.Wait() // all 10 goroutines are now blocked: 1 in fn, 9 in wg.Wait
close(release)
wg.Wait()
if calls.Load() != 1 || sharedCount.Load() != 10 {
t.Fatalf("calls=%d shared=%d", calls.Load(), sharedCount.Load())
}
// The key is forgotten afterwards: the next call runs fn again.
g.Do("user:1", func() (int, error) { calls.Add(1); return 0, nil })
if calls.Load() != 2 {
t.Fatal("result was cached; singleflight must not cache")
}
})
}
func TestPanicDoesNotStrandWaiters(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
var g Group[int, int]
release := make(chan struct{})
go func() {
defer func() { recover() }()
g.Do(1, func() (int, error) { <-release; panic("db exploded") })
}()
synctest.Wait()
done := make(chan error)
go func() {
_, err, _ := g.Do(1, func() (int, error) { return 0, nil })
done <- err
}()
synctest.Wait()
close(release)
if err := <-done; !errors.Is(err, ErrPanicked) {
t.Fatalf("waiter got %v", err)
}
})
}
Common wrong answer: Reading c.dups in the leader without the lock (a race, since waiters increment it under the lock), or forgetting to delete the key, which silently turns the deduplicator into a cache that never refreshes.
Follow-up: What does the real singleflight add? DoChan (a channel result you can select on with a timeout), Forget to drop a key early, and re-panicking the panic value in waiters instead of a sentinel error.
Q: Build a pipeline with graceful shutdown
Level: staff. Read items from a source, transform them with several workers, and write them to a sink. On shutdown, stop accepting new input but finish everything already accepted, then close the output so the consumer's range ends. The key is that only the intake stage watches the context; later stages drain until their input channel closes. In a real service, the context comes from signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM).
package pipeline
import (
"context"
"sync"
)
// Run moves items from in through transform (using workers goroutines) to the returned
// channel. When ctx is cancelled it stops reading in, finishes the items already taken,
// then closes the output. The caller must drain the output channel.
func Run[T, U any](ctx context.Context, in <-chan T, workers int, transform func(T) U) <-chan U {
accepted := make(chan T)
out := make(chan U)
go func() { // intake: the only stage that watches ctx
defer close(accepted)
for {
select {
case <-ctx.Done():
return
case v, ok := <-in:
if !ok {
return
}
accepted <- v // workers always drain accepted, so this can't block forever
}
}
}()
var wg sync.WaitGroup
for range workers {
wg.Go(func() {
for v := range accepted { // runs until intake closes accepted
out <- transform(v)
}
})
}
go func() { wg.Wait(); close(out) }()
return out
}
package pipeline
import (
"context"
"testing"
"testing/synctest"
"time"
)
func TestDrainsEverythingWithoutCancel(t *testing.T) {
in := make(chan int, 100)
for i := range 100 {
in <- i
}
close(in)
sum := 0
for v := range Run(context.Background(), in, 4, func(x int) int { return x * 2 }) {
sum += v
}
if sum != 9900 {
t.Fatalf("sum = %d", sum)
}
}
func TestGracefulShutdownLosesNothing(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
in := make(chan int, 100)
for i := range 100 {
in <- i
}
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
slow := func(x int) int { time.Sleep(10 * time.Millisecond); return x }
received := 0
for range Run(ctx, in, 4, slow) {
if received++; received == 10 {
cancel() // shut down mid-stream
}
}
// Every item taken from in was delivered; the rest are still in the channel.
if received+len(in) != 100 {
t.Fatalf("received %d, left %d: items lost", received, len(in))
}
if received >= 100 {
t.Fatal("cancel had no effect")
}
})
}
Common wrong answer: Making every stage select on ctx.Done() and return. Cancellation then drops the items that were in flight between stages: fine for a search request, data loss for a job queue.
Follow-up: How do you bound shutdown time? Give the drain its own deadline: after the first signal, start a timer (say 30 seconds, under the orchestrator's kill grace period); if the output hasn't closed by then, cancel a second, hard context that the transform also observes, and log what was abandoned.
Part 5: Output Prediction Puzzles
Cover the answer, predict, then check. Every output below came from go run . on Go 1.26.1 with go 1.26 in go.mod, except where a file pins an older language version.
Puzzle: Defer order, receivers and named results
package main
import "fmt"
type T struct{ name string }
func (t T) show() { fmt.Println("value:", t.name) }
func (t *T) showP() { fmt.Println("pointer:", t.name) }
func f() (n int) {
defer func() { n *= 2 }()
n = 1
return n + 2
}
func main() {
t := T{"a"}
defer t.show() // receiver copied now
defer t.showP() // receiver is &t
t.name = "c"
for i := range 2 {
defer func() { fmt.Println("closure", i) }()
}
fmt.Println(f())
}
Answer:
6
closure 1
closure 0
pointer: c
value: a
return n + 2 sets n to 3, then the deferred closure doubles it. The receiver is an argument, so it's evaluated when defer runs: the value receiver got a copy holding "a", the pointer receiver got &t and sees "c". Defers run last-in first-out. Trap: answering 3 for f(). Follow-up: Without the named result, would the defer change the return value? No. With an unnamed result, the deferred closure has no way to reach it.
Puzzle: Loop variables before and after Go 1.22
package main
import "fmt"
func main() {
var ptrs []*string
var fns []func()
for _, v := range []string{"a", "b", "c"} {
ptrs = append(ptrs, &v)
fns = append(fns, func() { fmt.Print(v) })
}
for _, f := range fns {
f()
}
fmt.Println(" |", *ptrs[0], ptrs[0] == ptrs[2])
}
Answer: abc | a false. Each iteration has its own v, so the closures and pointers all differ.
Now put //go:build go1.21 (and a blank line) above package main. A build constraint that names an older Go version downgrades that one file's language version, so the same loop gets the pre-1.22 semantics:
//go:build go1.21
package main
import "fmt"
func main() {
var ptrs []*string
var fns []func()
for _, v := range []string{"a", "b", "c"} {
ptrs = append(ptrs, &v)
fns = append(fns, func() { fmt.Print(v) })
}
for _, f := range fns {
f()
}
fmt.Println(" |", *ptrs[0], ptrs[0] == ptrs[2])
}
Answer: ccc | c true. One variable for the whole loop, last assigned "c", and every pointer is the same address. Trap: assuming the toolchain version decides it. It's the language version of the file (from go.mod or a //go:build line). Follow-up: How did teams migrate safely? The Go team's bisect tool and GOEXPERIMENT=loopvar let them find the tests whose behavior changed, and in practice nearly every change fixed a latent bug.
Puzzle: Nil interfaces
package main
import "fmt"
type E struct{}
func (*E) Error() string { return "E" }
func get() *E { return nil }
func main() {
var e1 error = get()
var e2 error
var p *E
fmt.Println(e1 == nil, e2 == nil, p == nil, e1 == p, e1 == e2)
}
Answer: false true true true false. e1 holds type *E with a nil pointer, so it isn't a nil interface. e1 == p converts p to error, giving the same (type, value) pair, so it's true. e2 is a truly nil interface, so e1 == e2 is false. Trap: expecting e1 == nil. Follow-up: How do you test "nil pointer inside"? reflect.ValueOf(e1).IsNil(), or better, make get return error.
Puzzle: Append inside a function
package main
import "fmt"
func add(s []int) {
s = append(s, 4)
s[0] = 99
}
func main() {
a := []int{1, 2, 3}
add(a)
fmt.Println(a)
b := make([]int, 3, 4)
copy(b, a)
add(b)
fmt.Println(b, len(b))
fmt.Println(b[:4])
}
Answer:
[99 2 3] 3
[99 2 3 4]
a is full (cap 3), so append allocated a new array and s[0] = 99 wrote to that. b has room, so append wrote into b's array and s[0] changed b[0], but the caller's length is still 3, so the 4 is only visible by reslicing. Trap: a single answer for both cases; the behavior depends on capacity. Follow-up: How do you make add visible to the caller? Return the slice: b = add(b), like append itself.
Puzzle: Map iteration
package main
import "fmt"
func main() {
m := map[string]int{"z": 26, "a": 1, "m": 13}
fmt.Println(m)
order := ""
for k := range m {
order += k
}
fmt.Println(len(order), order == "zam")
seen := 0
for k := range m {
if k == "a" {
m["b"] = 2 // added during iteration
}
seen++
}
fmt.Println(seen, len(m))
}
Answer: the first line is always map[a:1 m:13 z:26] (fmt sorts keys). The second may print 3 true or 3 false, changing from run to run. The third may print 3 4 or 4 4: the spec says an entry added during iteration may or may not be produced. Four runs here gave true/false and 3/4 in different combinations. Trap: reasoning from the printed map that iteration is sorted. Follow-up: Is deleting during iteration safe? Yes, and a deleted entry that hasn't been reached yet won't be produced.
Puzzle: Unbuffered send in main
package main
import "fmt"
func main() {
ch := make(chan int)
ch <- 1
fmt.Println(<-ch)
}
Answer: nothing is printed by fmt. The program dies with:
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan send]:
main.main()
and exit status 2. An unbuffered send waits for a receiver, and the only receiver is the next line of the same goroutine. The runtime notices that no goroutine can ever run again. With make(chan int, 1) it prints 1. Trap: expecting the receive on the next line to "pair up". Follow-up: Why doesn't a real server report this deadlock? Detection only fires when every goroutine is blocked. A server has goroutines in the network poller, so a deadlock between two goroutines just hangs them silently; find it with a goroutine profile.
Puzzle: select with several ready cases
package main
import "fmt"
func main() {
a := make(chan int, 1000)
b := make(chan int, 1000)
for range 1000 {
a <- 1
b <- 1
}
fromA, fromB := 0, 0
for range 1000 {
select { // both cases are always ready
case <-a:
fromA++
case <-b:
fromB++
}
}
fmt.Println(fromA+fromB, fromA > 400 && fromB > 400)
fmt.Println(fromA, fromB)
}
Answer: 1000 true, then a split that may print anything near even: runs here gave 532 468, 500 500, 501 499, 522 478. When several cases are ready, select picks uniformly at random. Trap: "the first case wins". Follow-up: How do you give one channel priority? A nested select: first try the high-priority channel with a default, and only then select on both.
Puzzle: Panic in another goroutine
package main
import (
"fmt"
"time"
)
func main() {
defer func() { fmt.Println("recovered in main:", recover()) }()
go func() {
panic("worker failed")
}()
time.Sleep(100 * time.Millisecond)
fmt.Println("main finished")
}
Answer: neither line prints. The output is:
panic: worker failed
goroutine 7 [running]:
main.main.func2()
.../main.go:11 +0x25
created by main.main in goroutine 1
with exit status 2 (the goroutine number may differ). main's deferred recover only covers the main goroutine, and an unrecovered panic in any goroutine ends the process without running other goroutines' defers. Trap: "the defer in main catches it". Follow-up: Where does the fix go? Inside the goroutine: a deferred recover at the top of its function (see safeGo in Part 2).
Puzzle: What range evaluates once
package main
import "fmt"
func main() {
arr := [3]int{1, 2, 3}
for i, v := range arr {
arr[2] = 100
if i == 2 {
fmt.Println("array:", v)
}
}
sl := []int{1, 2, 3}
for i, v := range sl {
sl[2] = 100
if i == 2 {
fmt.Println("slice:", v)
}
}
nums := []int{1, 2, 3}
for range nums {
nums = append(nums, 0) // the range length was fixed at the start
}
fmt.Println(len(nums))
}
Answer: array: 3, slice: 100, 6. The range expression is evaluated once, before the loop. For an array that means a copy of the array, so the write to arr[2] isn't seen. For a slice it copies only the header, so writes through it are seen, but the length is fixed at 3, which is why appending inside the loop ends after three iterations instead of looping forever. Trap: expecting 100 for the array, or an infinite loop. Follow-up: How do you avoid copying a big array in a range? Range over a pointer to it (range &arr) or a slice of it (range arr[:]).
Related Pages
- Go Cheat Sheet: syntax, standard library and commands for everything on this page
- Go Concurrency: the scheduler, channels,
syncand concurrency patterns in depth - Go Profiling: pprof, traces and benchmarking workflow
- Race Conditions and Deadlocks: the language-independent theory behind Parts 2 and 5
- Concurrency Interview Problems: more "build it" exercises
- LRU Cache (LLD), Rate Limiter (LLD), Pub-Sub (LLD): the Part 4 builds as design interviews
- JavaScript Interview Questions and Node.js Interview Questions: the same format for the JavaScript stack
- Rust Cheat Sheet: the other systems language that comes up in backend interviews