PrepStack › Backend › Go

Go interview cheat sheet

Types, slices & maps, interfaces, goroutines, channels, context and the runtime

Go interviews test whether you know how the language really behaves, not just its syntax: zero values, slices sharing a backing array, the nil interface trap, pointer vs value receivers, and error wrapping. Senior rounds go deep on concurrency: goroutines and the GMP scheduler, channels and select, sync, context, data races and worker pools. Snippets target Go 1.26; read the 15-minute revision first, then switch to Quiz mode and answer out loud.

15-minute revision

  1. Every type has a zero value: 0, "", false, nil for pointers, slices, maps, channels, funcs and interfaces. Design types so the zero value is useful (sync.Mutex, bytes.Buffer).
  2. := declares and assigns, only inside functions, and needs at least one new name on the left. var works everywhere and lets you skip the initial value.
  3. iota counts from 0 inside each const (...) block. Untyped constants have arbitrary precision until they are used.
  4. A string is an immutable byte sequence (usually UTF-8). len counts bytes; range over a string yields runes and byte offsets.
  5. Arrays are values with a fixed length. A slice is a 3-word header (pointer, len, cap) over a backing array; append may or may not reallocate.
  6. Sub-slices share memory. Use a full slice expression s[lo:hi:max] or slices.Clone to stop append from overwriting the parent.
  7. Reading a nil map returns zero values; writing panics. Map iteration order is randomised. Maps are not safe for concurrent writes.
  8. Embedding gives promotion, not inheritance: there is no virtual dispatch back into the outer type.
  9. Pointer receivers can mutate and avoid copies. The method set of T has only value-receiver methods; *T has both. Do not mix receiver kinds on one type.
  10. Interfaces are satisfied implicitly. An interface is nil only if both its type and value are nil, so returning a typed nil pointer as error is never == nil.
  11. Errors are values. Wrap with fmt.Errorf("...: %w", err), inspect with errors.Is (value) and errors.As / errors.AsType (type).
  12. defer runs LIFO when the function returns; its arguments are evaluated immediately. recover only works inside a deferred function.
  13. Goroutines are cheap (KB-size growable stacks) and scheduled by the runtime's GMP model onto GOMAXPROCS OS threads.
  14. Unbuffered channels synchronise sender and receiver. Only the sender closes. Sending on a closed channel panics; nil channels block forever.
  15. Pass context.Context as the first argument; always defer cancel(). Run tests with -race because data races are undefined behaviour.
  16. Since Go 1.22 each for iteration has its own loop variable, and ServeMux supports patterns like GET /users/{id}.

Language foundations

Philosophy, zero values, var vs := & constants

Go is a small, explicit, statically typed language where every variable starts at a usable zero value.

  • Philosophy: simplicity over cleverness, composition over inheritance, explicit errors instead of exceptions, fast compiles, one formatting style (gofmt), and concurrency built in.
  • Statically typed and compiled to a single native binary with a garbage collector. No classes, no implicit numeric conversions, no unused imports or unused local variables.
  • Zero values: numbers 0, strings "", bools false, and nil for pointers, slices, maps, channels, functions and interfaces. Structs are zeroed field by field.
  • var x T or var x = v works at package and function level. x := v is the short form, only inside functions, and needs at least one new variable on the left.
  • Constants are compile-time values. Untyped constants (const big = 1 << 100) keep arbitrary precision and take a type only when used.
  • iota starts at 0 in each const block and increases by one per line. Use it for enums and bit flags; skip a value with _.

Interview questions

  • What is the zero value in Go and why does it matter?
  • Difference between var and :=?
  • Why does Go not have classes, inheritance or exceptions?

Strings, bytes & runes

A string is an immutable slice of bytes; a rune is an int32 Unicode code point.

  • string is a read-only byte sequence, usually UTF-8. len(s) is the number of bytes, not characters.
  • Indexing s[i] gives a byte (uint8). for i, r := range s decodes UTF-8 and yields the byte offset and a rune (int32).
  • Convert with []byte(s) and []rune(s). Both conversions copy the data (the compiler can sometimes avoid it).
  • Strings are immutable, so s += x in a loop copies every time. Use strings.Builder (or bytes.Buffer) to build strings.
  • Use unicode/utf8 for rune counting and validation, and the strings package for searching, splitting and trimming.

Interview questions

  • What is the difference between a byte and a rune?
  • Why does len("世界") return 6?
  • How do you build a large string efficiently?

Collections

Arrays vs slices, len, cap & append

Arrays are fixed-size values; slices are small views (pointer, len, cap) over an array and are what you use day to day.

  • An array [3]int has its length in its type. Assigning or passing it copies all elements. [3]int and [4]int are different types.
  • A slice []int is a header with a pointer to a backing array, a length (elements visible) and a capacity (room until the end of the backing array).
  • append writes in place if len < cap. Otherwise it allocates a bigger array, copies, and returns a slice pointing to the new array. Always use the result: s = append(s, v).
  • Growth is roughly 2x for small slices and gradually closer to 1.25x for large ones (the threshold is 256 elements), then rounded up to a memory size class.
  • s[lo:hi] has len hi-lo and cap cap(s)-lo. make([]T, len, cap) pre-allocates when you know the size.
  • A nil slice (var s []int) and an empty slice ([]int{}) both have len 0 and work with append and range; only the nil one is == nil (and JSON-encodes as null).

Interview questions

  • Difference between an array and a slice?
  • How does append grow a slice?
  • Nil slice vs empty slice?

Slice gotchas: shared backing arrays

Sub-slices and slices passed to functions share memory, so append and writes can leak into each other.

  • sub := s[:2] shares the backing array. If sub has spare capacity, append(sub, x) overwrites s[2].
  • A full slice expression s[lo:hi:max] caps the capacity, so the next append must allocate and the parent is safe.
  • A function receives a copy of the header. Writes to elements are visible to the caller, but an append that changes len is not (the caller's len is unchanged).
  • Keeping a small sub-slice of a huge array keeps the whole array alive in memory. Copy what you need with slices.Clone or copy.
  • Never share a slice between goroutines for writes without synchronisation; disjoint index writes are fine, append is not.

Interview questions

  • Why did appending to a sub-slice change the original slice?
  • A function appends to a slice parameter but the caller doesn't see the new element. Why?
  • How can slices cause memory leaks?

Maps: nil maps, order & concurrency

Maps are hash tables with comparable keys; read a nil map freely, never write to one, and never write from two goroutines.

  • Create with make(map[K]V) or a literal. Keys must be comparable (no slices, maps or functions as keys).
  • v, ok := m[k] is the comma-ok idiom: a missing key returns the zero value and ok == false.
  • A nil map behaves like an empty map for reads, len and range, but assigning to it panics.
  • Iteration order is random on purpose. Sort the keys (slices.Sorted(maps.Keys(m))) for stable output. fmt prints maps sorted.
  • Maps are not safe for concurrent use. A concurrent write is detected by the runtime and crashes with fatal error: concurrent map writes. Use a sync.Mutex/RWMutex, or sync.Map for append-mostly caches.
  • A map value is a pointer to a runtime structure, so passing a map to a function lets it modify the caller's map. Map elements are not addressable: &m[k] does not compile.

Interview questions

  • What happens when you write to a nil map?
  • Why is map iteration order random?
  • Is a Go map safe for concurrent use? What are the options?

Types, methods & interfaces

Structs & embedding

Structs group fields; embedding promotes an inner type's fields and methods, which is composition, not inheritance.

  • A struct is a value type: assignment copies every field. Structs are comparable with == when all fields are comparable.
  • Field names starting with an upper-case letter are exported (visible outside the package); lower-case ones are private to the package.
  • Embedding a type (a field with no name) promotes its fields and methods, so d.Name works instead of d.Animal.Name.
  • The outer type can shadow a promoted method. But the inner type's methods still see only the inner type: there is no virtual dispatch.
  • Embedding an interface in a struct, or an interface in an interface (io.ReadWriter), is common for composing behaviour.
  • Go has no constructors; the convention is a NewThing(...) *Thing function. Struct tags (for JSON, DB) are read through reflection.

Interview questions

  • Does Go support inheritance?
  • What is the difference between embedding and a named field?
  • Can you compare two structs?

Methods: pointer vs value receivers

Use a pointer receiver when the method mutates or the struct is large; value receivers work on a copy.

  • A method is a function with a receiver. You can define methods on any named type in your package (type Celsius float64), not only structs.
  • Value receiver (c Counter): gets a copy, so changes are lost. Pointer receiver (c *Counter): can mutate and avoids copying.
  • Go auto-adjusts calls: v.PtrMethod() becomes (&v).PtrMethod() if v is addressable, and p.ValMethod() becomes (*p).ValMethod().
  • Method sets decide interface satisfaction: type T has only value-receiver methods; *T has both. So if a method has a pointer receiver, only *T satisfies the interface.
  • Rule of thumb: if any method needs a pointer receiver, use pointer receivers for all methods of that type for consistency. Never copy types holding a sync.Mutex.

Interview questions

  • When would you use a pointer receiver vs a value receiver?
  • Why does var s Shape = MyType{} fail when the method has a pointer receiver?
  • What is a method value vs a method expression?

Interfaces, any, type switches & the nil trap

Interfaces are satisfied implicitly; an interface holding a typed nil pointer is not nil.

  • An interface is a set of method signatures. A type satisfies it implicitly by having those methods; there is no implements keyword.
  • Keep interfaces small and define them where they are used (consumer side). "Accept interfaces, return structs."
  • any is an alias for interface{}, the empty interface that every type satisfies.
  • A type assertion v, ok := x.(T) extracts the concrete value; without ok a wrong type panics. A type switch switch v := x.(type) branches on the dynamic type.
  • An interface value is a pair (type, value). It is nil only when both are nil. Storing a nil *MyErr makes the type non-nil, so err != nil.
  • Compile-time check that a type implements an interface: var _ Shape = (*Rect)(nil).

Interview questions

  • How does Go know a type implements an interface?
  • Why can an error be non-nil even though the pointer inside it is nil?
  • Difference between a type assertion and a type switch?
  • What does "accept interfaces, return structs" mean?

Generics: type parameters & constraints

Since Go 1.18, functions and types can take type parameters constrained by interfaces.

  • Syntax: func Map[T, U any](xs []T, f func(T) U) []U. Type arguments are usually inferred from the arguments.
  • A constraint is an interface. It can list methods and/or a type set: interface{ ~int | ~float64 }. ~int also accepts types whose underlying type is int.
  • Built-in constraints: any, comparable (supports ==, needed for map keys) and cmp.Ordered (supports <).
  • Generic types: type Stack[T any] struct{ items []T }. Methods use the type's parameters but cannot declare new type parameters of their own.
  • Use var zero T to return a zero value of a type parameter.
  • Go 1.26 lets a generic type refer to itself in its own constraint, e.g. type Adder[A Adder[A]] interface{ Add(A) A }.

Interview questions

  • What does the ~ mean in a constraint?
  • Difference between any and comparable?
  • When would you choose generics over an interface?

Errors & control flow

Errors: values, wrapping, Is & As

Errors are ordinary values returned last; wrap them with %w and inspect the chain with errors.Is and errors.As.

  • error is a one-method interface: Error() string. Functions return it as the last value, and callers check if err != nil right away.
  • Sentinel errors are package-level values like io.EOF or var ErrNotFound = errors.New("not found"). Custom error types carry extra fields.
  • fmt.Errorf("load config: %w", err) wraps the error, adding context while keeping the original. %v formats the text only and breaks the chain.
  • errors.Is(err, ErrNotFound) walks the chain comparing values. errors.As(err, &target) finds the first error of a type. Go 1.26 adds generic errors.AsType[*T](err).
  • errors.Join(e1, e2) (and multiple %w in one Errorf) builds an error tree; Is/As search all branches.
  • Handle an error once: either log it or return it with context, not both.

Interview questions

  • Why does Go use error values instead of exceptions?
  • Difference between errors.Is and errors.As?
  • What is the difference between %w and %v in fmt.Errorf?

defer, panic & recover

Deferred calls run LIFO when the function returns, with arguments evaluated at the defer line; recover in a defer stops a panic.

  • defer f(x) schedules f to run when the surrounding function returns (not the block), including during a panic.
  • Multiple defers run in LIFO order (a stack).
  • Arguments are evaluated immediately when defer executes. A deferred closure, instead, reads variables when it runs.
  • Deferred closures can modify named return values, which is how you set err after a recover or add cleanup errors.
  • panic unwinds the stack running defers. recover() returns the panic value only when called directly in a deferred function; elsewhere it returns nil.
  • Use panic for programmer bugs and impossible states. A panic in a goroutine that is not recovered crashes the whole program; one goroutine cannot recover another's panic.

Interview questions

  • In what order do deferred calls run, and when are their arguments evaluated?
  • How do panic and recover work?
  • When is it OK to use panic?

Concurrency

Goroutines & the GMP scheduler

Goroutines are cheap user-space threads multiplexed onto OS threads by the runtime's G-M-P scheduler.

  • go f() starts a goroutine. It starts with a small stack (a few KB) that grows and shrinks as needed, so a program can run hundreds of thousands of them.
  • When main returns the program exits and all goroutines are killed. Wait for them with sync.WaitGroup, channels or errgroup.
  • G = goroutine, M = OS thread, P = processor (a scheduling context with a local run queue). An M must hold a P to run Go code. There are GOMAXPROCS Ps.
  • Work stealing: an idle P takes half of another P's run queue, or checks the global queue and the network poller.
  • Blocking syscalls hand the P to another M; network I/O parks the G on the netpoller (epoll/kqueue) instead of blocking a thread.
  • Scheduling is preemptive: since Go 1.14 long-running loops are interrupted with signals (asynchronous preemption). Go 1.25 made GOMAXPROCS respect container CPU limits on Linux.
  • Go 1.25 added wg.Go(f), which does Add(1), starts the goroutine and calls Done for you.

Interview questions

  • What is a goroutine and how is it different from a thread?
  • Explain the GMP model.
  • What does GOMAXPROCS control?
  • What happens to running goroutines when main returns?

Channels, select & timeouts

Channels pass values between goroutines and synchronise them; select waits on several channel operations at once.

  • Unbuffered make(chan T): a send blocks until a receiver takes it, a hand-off that synchronises both sides. Buffered make(chan T, n): sends block only when the buffer is full.
  • Only the sender closes a channel, to say "no more values". Receiving from a closed channel returns the zero value immediately; use v, ok := <-ch to detect it. for v := range ch stops at close.
  • Send on a closed channel panics; closing twice panics. Send or receive on a nil channel blocks forever.
  • Directional types chan<- T (send-only) and <-chan T (receive-only) document intent and are checked by the compiler.
  • select blocks until one case can proceed and picks randomly if several are ready. A default case makes it non-blocking.
  • Timeouts: case <-time.After(d) or a context's Done(). Setting a channel variable to nil disables its case in a select.

Interview questions

  • Difference between buffered and unbuffered channels?
  • What happens when you send to or close a closed channel? And with a nil channel?
  • How does select choose between ready cases?
  • Who should close a channel and why?

sync: WaitGroup, Mutex, RWMutex, Once & atomics

Use the sync package to protect shared memory when channels are not the natural fit.

  • "Don't communicate by sharing memory; share memory by communicating." Still, a mutex is often simpler for guarding a map or counter.
  • sync.WaitGroup: Add(n) before starting, Done() in each goroutine, Wait() to block. Go 1.25's wg.Go(f) wraps all three.
  • sync.Mutex: Lock/Unlock, usually mu.Lock(); defer mu.Unlock(). Not reentrant: locking twice in the same goroutine deadlocks.
  • sync.RWMutex: many readers (RLock) or one writer (Lock). Worth it only when reads heavily dominate and critical sections are not tiny.
  • sync.Once runs initialisation exactly once, even with concurrent callers. sync.OnceValue/OnceValues (Go 1.21) return the cached result.
  • sync/atomic types (atomic.Int64, atomic.Bool, atomic.Pointer[T]) give lock-free counters and flags. sync.Pool reuses temporary objects to cut GC pressure.

Interview questions

  • Mutex vs RWMutex?
  • Is sync.Mutex reentrant?
  • When would you use sync.Once?
  • When would you choose atomics over a mutex?

Worker pools, pipelines, fan-out & fan-in

Bound concurrency with a fixed set of workers reading from a jobs channel, and merge results back into one channel.

  • Worker pool: N goroutines range over a jobs channel and send to results. It caps concurrency (CPU, DB connections, API rate limits).
  • Fan-out: several goroutines read from the same channel to share work. Fan-in: merge several channels into one.
  • Pipeline: stages connected by channels (gen → square → sum). Each stage closes its output when its input is done.
  • Close results only after all workers finish: one goroutine does wg.Wait(); close(results).
  • A buffered channel used as a semaphore (sem := make(chan struct{}, N)) is a simpler way to cap concurrent goroutines.
  • In production, golang.org/x/sync/errgroup adds error propagation, context cancellation and SetLimit(n) on top of this pattern.

Interview questions

  • How would you implement a worker pool in Go?
  • How do you limit the number of concurrent HTTP calls to 10?
  • Scenario: a pipeline hangs when the consumer returns early on error. Why and how do you fix it?

context: cancellation, deadlines & values

A context.Context carries cancellation, deadlines and request-scoped values across API boundaries and goroutines.

  • Pass it as the first parameter, named ctx. Never store it in a struct or pass nil (use context.Background() or context.TODO()).
  • WithCancel, WithTimeout, WithDeadline return a child context and a cancel func. Always defer cancel() to release timers and children.
  • Cancelling a parent cancels all its children, so one cancelled HTTP request stops every DB query and RPC beneath it.
  • Long-running code checks <-ctx.Done() in a select, or ctx.Err() in loops. Err() returns context.Canceled or context.DeadlineExceeded.
  • WithCancelCause / context.Cause (1.20) record why it was cancelled. AfterFunc (1.21) runs a callback on cancellation; WithoutCancel (1.21) detaches from the parent.
  • WithValue is only for request-scoped data (trace ID, auth info), with an unexported key type. Never use it for optional function parameters.

Interview questions

  • What is context.Context used for?
  • Why must you always call the cancel function?
  • Difference between context.Background() and context.TODO()?
  • What should and shouldn't go into context values?

Data races, race detector & loop variables

A data race is unsynchronised concurrent access with at least one write; detect it with -race. Go 1.22 made loop variables per-iteration.

  • A data race: two goroutines access the same memory at the same time, at least one writes, and there is no happens-before ordering. The result is undefined, not just a wrong count.
  • The race detector (go test -race, go run -race, go build -race) instruments memory accesses and reports races that actually happen during the run. It adds roughly 5–10x CPU and memory overhead.
  • Fix races with a mutex, atomics, or by giving ownership to one goroutine and communicating with channels.
  • A race condition is broader: a logic bug that depends on timing (check-then-act), which can exist even without a data race.
  • Go 1.22 loop variables: each iteration of a for loop now has its own copy of the variable, so closures and goroutines capture the expected value. It applies when the module's go line is 1.22 or later.
  • Before 1.22, for i := ... had one shared variable, so go func(){ use(i) }() often saw the last value; the old fix was i := i.

Interview questions

  • What is a data race and how do you detect it?
  • Data race vs race condition?
  • What changed about loop variables in Go 1.22?
  • Is count++ atomic in Go?

Runtime, tooling & web

Memory, escape analysis & garbage collection

The compiler decides stack vs heap with escape analysis; heap objects are freed by a concurrent mark-and-sweep GC.

  • Escape analysis runs at compile time. A value stays on the goroutine's stack if the compiler can prove it does not outlive the function; otherwise it is moved to the heap.
  • Common reasons to escape: returning a pointer to a local, storing it in an interface or a long-lived structure, capturing it in a closure that outlives the call, or a size unknown at compile time.
  • See decisions with go build -gcflags=-m. Stack allocation is nearly free; heap allocation costs allocator time and later GC work.
  • The GC is a concurrent, tri-colour, mark-and-sweep, non-moving collector with short stop-the-world phases. Go 1.26 enables the Green Tea GC by default, which scans small objects with better memory locality.
  • Tune with GOGC (default 100: next GC when the heap grows 100% over the live heap) and GOMEMLIMIT (a soft total memory limit, useful in containers).
  • Reduce GC pressure: fewer allocations, pre-sized slices and maps, sync.Pool for hot temporary buffers, values instead of pointers in big slices.

Interview questions

  • What is escape analysis?
  • How does Go's garbage collector work?
  • What do GOGC and GOMEMLIMIT do?
  • How would you reduce allocations in a hot path?

Packages, modules, testing & benchmarks

Code lives in packages inside a module defined by go.mod; tests are _test.go files run by go test.

  • A package is a directory of files with the same package name. Upper-case identifiers are exported. Import cycles are compile errors. internal/ packages can only be imported by code under the parent of internal.
  • A module is a tree of packages with a go.mod (module path, go version, requires) and go.sum (checksums). Dependencies use Minimal Version Selection: the minimum version satisfying all requirements.
  • Key commands: go mod init, go get pkg@v1.2.3, go mod tidy, go build, go vet, go test ./.... Major versions v2+ change the import path (/v2).
  • init() functions run once per package after variables are initialised, before main. Keep them minimal.
  • Tests: func TestXxx(t *testing.T) in _test.go files. Table-driven tests with t.Run subtests are the idiom. t.Parallel() runs subtests concurrently.
  • Benchmarks: func BenchmarkXxx(b *testing.B) with for b.Loop() (Go 1.24+). Fuzzing: func FuzzXxx(f *testing.F). Examples: func ExampleXxx() with an // Output: comment are verified by go test.

Interview questions

  • What is the difference between a package and a module?
  • What are table-driven tests?
  • How does Go choose dependency versions?
  • How do you write and read a benchmark?

net/http servers & Go 1.22 routing

The standard library ships a production-grade HTTP server; since Go 1.22 ServeMux matches methods and path wildcards.

  • A handler is anything with ServeHTTP(http.ResponseWriter, *http.Request); http.HandlerFunc adapts a plain function. Each request runs in its own goroutine, so shared state needs locking.
  • Go 1.22 patterns: "GET /users/{id}" (method + wildcard), r.PathValue("id"), {path...} for the rest of the path, and {$} to match only the exact path.
  • Most specific pattern wins, independent of registration order. Two overlapping patterns where neither is more specific cause a panic at registration. A wrong method gets 405 with an Allow header.
  • GET patterns also match HEAD. A pattern ending in / (like /static/) still matches everything below it.
  • Middleware is a function func(http.Handler) http.Handler that wraps a handler for logging, auth, recovery or timeouts.
  • Production setup: set ReadHeaderTimeout/ReadTimeout/WriteTimeout/IdleTimeout on http.Server (the defaults have none) and use srv.Shutdown(ctx) for graceful shutdown. r.Context() is cancelled when the client goes away.

Interview questions

  • What changed in net/http routing in Go 1.22?
  • How does the Go HTTP server handle concurrency?
  • How do you gracefully shut down an HTTP server?
  • How do you write middleware in Go?