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
- Every type has a zero value:
0,"",false,nilfor pointers, slices, maps, channels, funcs and interfaces. Design types so the zero value is useful (sync.Mutex,bytes.Buffer). :=declares and assigns, only inside functions, and needs at least one new name on the left.varworks everywhere and lets you skip the initial value.iotacounts from 0 inside eachconst (...)block. Untyped constants have arbitrary precision until they are used.- A string is an immutable byte sequence (usually UTF-8).
lencounts bytes;rangeover a string yields runes and byte offsets. - Arrays are values with a fixed length. A slice is a 3-word header (pointer, len, cap) over a backing array;
appendmay or may not reallocate. - Sub-slices share memory. Use a full slice expression
s[lo:hi:max]orslices.Cloneto stopappendfrom overwriting the parent. - Reading a nil map returns zero values; writing panics. Map iteration order is randomised. Maps are not safe for concurrent writes.
- Embedding gives promotion, not inheritance: there is no virtual dispatch back into the outer type.
- Pointer receivers can mutate and avoid copies. The method set of
Thas only value-receiver methods;*Thas both. Do not mix receiver kinds on one type. - Interfaces are satisfied implicitly. An interface is nil only if both its type and value are nil, so returning a typed nil pointer as
erroris never== nil. - Errors are values. Wrap with
fmt.Errorf("...: %w", err), inspect witherrors.Is(value) anderrors.As/errors.AsType(type). deferruns LIFO when the function returns; its arguments are evaluated immediately.recoveronly works inside a deferred function.- Goroutines are cheap (KB-size growable stacks) and scheduled by the runtime's GMP model onto
GOMAXPROCSOS threads. - Unbuffered channels synchronise sender and receiver. Only the sender closes. Sending on a closed channel panics; nil channels block forever.
- Pass
context.Contextas the first argument; alwaysdefer cancel(). Run tests with-racebecause data races are undefined behaviour. - Since Go 1.22 each
foriteration has its own loop variable, andServeMuxsupports patterns likeGET /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"", boolsfalse, andnilfor pointers, slices, maps, channels, functions and interfaces. Structs are zeroed field by field. var x Torvar x = vworks at package and function level.x := vis 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. iotastarts at 0 in eachconstblock 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
varand:=? - 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.
stringis a read-only byte sequence, usually UTF-8.len(s)is the number of bytes, not characters.- Indexing
s[i]gives abyte(uint8).for i, r := range sdecodes 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 += xin a loop copies every time. Usestrings.Builder(orbytes.Buffer) to build strings. - Use
unicode/utf8for rune counting and validation, and thestringspackage 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]inthas its length in its type. Assigning or passing it copies all elements.[3]intand[4]intare different types. - A slice
[]intis a header with a pointer to a backing array, a length (elements visible) and a capacity (room until the end of the backing array). appendwrites in place iflen < 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 lenhi-loand capcap(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 withappendandrange; only the nil one is== nil(and JSON-encodes asnull).
Interview questions
- Difference between an array and a slice?
- How does
appendgrow 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. Ifsubhas spare capacity,append(sub, x)overwritess[2].- A full slice expression
s[lo:hi:max]caps the capacity, so the nextappendmust allocate and the parent is safe. - A function receives a copy of the header. Writes to elements are visible to the caller, but an
appendthat 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.Cloneorcopy. - Never share a slice between goroutines for writes without synchronisation; disjoint index writes are fine,
appendis 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 andok == false.- A nil map behaves like an empty map for reads,
lenandrange, but assigning to it panics. - Iteration order is random on purpose. Sort the keys (
slices.Sorted(maps.Keys(m))) for stable output.fmtprints 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 async.Mutex/RWMutex, orsync.Mapfor 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.Nameworks instead ofd.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(...) *Thingfunction. 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()ifvis addressable, andp.ValMethod()becomes(*p).ValMethod(). - Method sets decide interface satisfaction: type
Thas only value-receiver methods;*Thas both. So if a method has a pointer receiver, only*Tsatisfies 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
implementskeyword. - Keep interfaces small and define them where they are used (consumer side). "Accept interfaces, return structs."
anyis an alias forinterface{}, the empty interface that every type satisfies.- A type assertion
v, ok := x.(T)extracts the concrete value; withoutoka wrong type panics. A type switchswitch v := x.(type)branches on the dynamic type. - An interface value is a pair (type, value). It is
nilonly when both are nil. Storing a nil*MyErrmakes the type non-nil, soerr != 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 }.~intalso accepts types whose underlying type isint. - Built-in constraints:
any,comparable(supports==, needed for map keys) andcmp.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 Tto 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
anyandcomparable? - 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.
erroris a one-method interface:Error() string. Functions return it as the last value, and callers checkif err != nilright away.- Sentinel errors are package-level values like
io.EOForvar 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.%vformats 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 genericerrors.AsType[*T](err).errors.Join(e1, e2)(and multiple%win oneErrorf) builds an error tree;Is/Assearch 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.Isanderrors.As? - What is the difference between
%wand%vinfmt.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)schedulesfto 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
deferexecutes. A deferred closure, instead, reads variables when it runs. - Deferred closures can modify named return values, which is how you set
errafter a recover or add cleanup errors. panicunwinds 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
panicandrecoverwork? - 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
mainreturns the program exits and all goroutines are killed. Wait for them withsync.WaitGroup, channels orerrgroup. - 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
GOMAXPROCSPs. - 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
GOMAXPROCSrespect container CPU limits on Linux. - Go 1.25 added
wg.Go(f), which doesAdd(1), starts the goroutine and callsDonefor 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. Bufferedmake(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 := <-chto detect it.for v := range chstops 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. selectblocks until one case can proceed and picks randomly if several are ready. Adefaultcase makes it non-blocking.- Timeouts:
case <-time.After(d)or a context'sDone(). 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
selectchoose 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'swg.Go(f)wraps all three.sync.Mutex:Lock/Unlock, usuallymu.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.Onceruns initialisation exactly once, even with concurrent callers.sync.OnceValue/OnceValues(Go 1.21) return the cached result.sync/atomictypes (atomic.Int64,atomic.Bool,atomic.Pointer[T]) give lock-free counters and flags.sync.Poolreuses temporary objects to cut GC pressure.
Interview questions
- Mutex vs RWMutex?
- Is
sync.Mutexreentrant? - 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
rangeover ajobschannel and send toresults. 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
resultsonly after all workers finish: one goroutine doeswg.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/errgroupadds error propagation, context cancellation andSetLimit(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 (usecontext.Background()orcontext.TODO()). WithCancel,WithTimeout,WithDeadlinereturn a child context and acancelfunc. Alwaysdefer 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 aselect, orctx.Err()in loops.Err()returnscontext.Canceledorcontext.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.WithValueis 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.Contextused for? - Why must you always call the cancel function?
- Difference between
context.Background()andcontext.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
forloop now has its own copy of the variable, so closures and goroutines capture the expected value. It applies when the module'sgoline is 1.22 or later. - Before 1.22,
for i := ...had one shared variable, sogo func(){ use(i) }()often saw the last value; the old fix wasi := 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) andGOMEMLIMIT(a soft total memory limit, useful in containers). - Reduce GC pressure: fewer allocations, pre-sized slices and maps,
sync.Poolfor 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
packagename. Upper-case identifiers are exported. Import cycles are compile errors.internal/packages can only be imported by code under the parent ofinternal. - A module is a tree of packages with a
go.mod(module path,goversion,requires) andgo.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, beforemain. Keep them minimal.- Tests:
func TestXxx(t *testing.T)in_test.gofiles. Table-driven tests witht.Runsubtests are the idiom.t.Parallel()runs subtests concurrently. - Benchmarks:
func BenchmarkXxx(b *testing.B)withfor b.Loop()(Go 1.24+). Fuzzing:func FuzzXxx(f *testing.F). Examples:func ExampleXxx()with an// Output:comment are verified bygo 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.HandlerFuncadapts 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
Allowheader. GETpatterns also matchHEAD. A pattern ending in/(like/static/) still matches everything below it.- Middleware is a function
func(http.Handler) http.Handlerthat wraps a handler for logging, auth, recovery or timeouts. - Production setup: set
ReadHeaderTimeout/ReadTimeout/WriteTimeout/IdleTimeoutonhttp.Server(the defaults have none) and usesrv.Shutdown(ctx)for graceful shutdown.r.Context()is cancelled when the client goes away.
Interview questions
- What changed in
net/httprouting 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?