Go (Golang) Interview Questions
Go systems programming interview track: goroutine scheduling (GMP model), channels, memory escape analysis, interfaces, defer semantics, and context cancellation.
Practice Go (Golang) Interview Questions
Showing 16 of 16 technical questions with engineering explanations
How do Go slices differ from arrays under the hood, and what happens when append() exceeds capacity?
Senior Engineering Answer
An array in Go has a fixed length as part of its type and is copied by value when assigned or passed. A slice is a 3-word header (24 bytes on 64-bit) containing a pointer to an underlying array, length (len), and capacity (cap). When append() fits within cap, it mutates the shared backing array in place; when len equals cap, Go allocates a new larger backing array (roughly doubling for small slices, scaling smoothly ~1.25x for larger ones), copies elements over, and returns a slice header pointing to the new array.
a := make([]int, 2, 4) a[0], a[1] = 1, 2 b := append(a, 3) // Mutates shared backing array at index 2 c := append(b, 4, 5) // Exceeds cap=4; allocates a new backing array
Returning a sub-slice of a huge buffer (e.g., data[:10] from a 10MB slice): the 10-byte sub-slice keeps a pointer to the entire 10MB backing array, preventing the GC from reclaiming it unless you copy into a fresh slice.
What is the difference between a nil slice and an empty slice, and how does encoding/json serialize each?
Senior Engineering Answer
A nil slice (var s []int) has a nil backing pointer, len=0, and cap=0, allocating zero heap memory. An empty slice (s := []int{} or make([]int, 0)) has a non-nil pointer (pointing to runtime.zerobase) with len=0 and cap=0. Both behave identically with len(), cap(), range, and append(). However, encoding/json marshals a nil slice as JSON null, whereas an empty slice marshals as JSON [].
var nilSlice []string
emptySlice := []string{}
// json.Marshal(nilSlice) -> "null"
// json.Marshal(emptySlice) -> "[]"Pre-allocating slices with make([]T, n) instead of make([]T, 0, n) and then calling append(): make([]T, n) initializes n zero-valued elements, so append() puts new items starting at index n.
How do Go maps behave under concurrent access, and why is map iteration order randomized?
Senior Engineering Answer
Standard Go maps are not safe for concurrent writes (or concurrent read + write); the runtime detects concurrent modification and throws a fatal unrecoverable runtime panic (not catchable with recover()). For concurrent access, protect maps with sync.Mutex/sync.RWMutex or use sync.Map for read-mostly or disjoint-key workloads. Map iteration order is intentionally randomized by the Go runtime (via a random starting bucket/offset) so callers never accidentally rely on deterministic ordering.
type SafeCache struct {
mu sync.RWMutex
m map[string]string
}
func (c *SafeCache) Get(k string) (string, bool) {
c.mu.RLock()
defer c.mu.RUnlock()
v, ok := c.m[k]
return v, ok
}Writing to a nil map (var m map[string]int; m["a"] = 1) causes an immediate panic, whereas reading from a nil map safely returns the zero value.
How does defer work in Go, including execution order, argument evaluation timing, and named return values?
Senior Engineering Answer
Deferred calls execute in LIFO (Last-In, First-Out) order immediately before the enclosing function returns, even if a panic occurs. Crucially, the arguments to a deferred function are evaluated immediately when the defer statement is executed, not when the deferred function runs. Additionally, a deferred closure can read and modify named return values after the return expression is evaluated.
func readValue() (val int) {
x := 10
defer func(snapshot int) {
val += snapshot // Sees snapshot=10, modifies named return val
}(x)
x = 99
return 5 // Returns 15
}Using defer inside a long-running loop (e.g., opening 10,000 files in a for loop with defer f.Close()): deferred calls do not run until the outer function exits, leaking file descriptors until the loop finishes.
How does Go's GMP scheduler multiplex goroutines onto OS threads, including network polling and syscalls?
Senior Engineering Answer
The Go scheduler coordinates G (goroutine, starting with a 2KB growable stack), M (OS thread), and P (logical processor, defaulting to GOMAXPROCS, each holding a local run queue and mcache). When a G performs a blocking syscall (like file I/O), the M blocks in the kernel; the runtime detaches P from that M and hands P to another idle or newly created M so remaining Gs keep running. For network I/O, Go uses non-blocking sockets with the netpoller (epoll/kqueue/IOCP), parking only the G while M+P immediately switch to other Gs. Idle Ps steal half the local run queue from busy Ps (work stealing).
// GOMAXPROCS controls the number of logical processors P executing Go code runtime.GOMAXPROCS(runtime.NumCPU())
Confusing GOMAXPROCS with the max number of OS threads: GOMAXPROCS limits P (threads simultaneously executing Go user code), while M (blocked threads in cgo/syscalls) can grow up to 10,000 by default.
What are the behavioral differences between unbuffered channels, buffered channels, and nil/closed channels?
Senior Engineering Answer
An unbuffered channel (make(chan T)) performs a synchronous rendezvous: send blocks until a receiver is ready and vice versa. A buffered channel (make(chan T, n)) lets sends proceed without blocking until the buffer has n items. Sending to a closed channel panics; receiving from a closed channel never blocks and immediately yields remaining buffered items followed by zero values with ok=false. Both sending to and receiving from a nil channel block forever—which is useful inside a select statement to dynamically disable a case.
// Select with nil channel trick to merge two channels cleanly
for ch1 != nil || ch2 != nil {
select {
case v, ok := <-ch1:
if !ok { ch1 = nil; continue }
process(v)
case v, ok := <-ch2:
if !ok { ch2 = nil; continue }
process(v)
}
}Closing a channel from the receiver side or closing a channel twice—both panic. Always have the producer (or a coordinated single closer via sync.Once) close a channel.
Explain Go error wrapping with %w, errors.Is, and errors.As, and when to use each.
Senior Engineering Answer
Since Go 1.13, fmt.Errorf("...: %w", err) wraps an underlying error while preserving the error chain via an Unwrap() method. errors.Is(err, target) traverses the chain (including joined multi-errors from errors.Join in Go 1.20+) to match a sentinel error value like sql.ErrNoRows. errors.As(err, &typedTarget) traverses the chain to extract a specific concrete error type (e.g., *net.OpError) so callers can inspect structured fields.
var ErrNotFound = errors.New("record not found")
func loadUser(id string) error {
return fmt.Errorf("loadUser %s: %w", id, ErrNotFound)
}
// Caller:
if errors.Is(err, ErrNotFound) {
// Returns HTTP 404 even though ErrNotFound was wrapped
}Comparing wrapped errors with == (err == sql.ErrNoRows) or formatting with %v instead of %w: %v converts the error to a plain string and destroys the chain for errors.Is/errors.As.
How do Go interfaces work internally (eface vs iface), and why does a typed nil fail err != nil?
Senior Engineering Answer
An interface value in Go is a two-word fat pointer: (type pointer, data pointer). Empty interfaces (any / interface{}) use eface (_type, data), while non-empty interfaces use iface (*itab, data) where itab caches the concrete type and its method dispatch table. An interface is nil ONLY when both its type and data pointers are nil. If a function returns a concrete pointer (*MyError)(nil) typed as error, the interface holds (type=*MyError, data=nil), so err != nil evaluates to true!
type MyErr struct{}
func (e *MyErr) Error() string { return "fail" }
func badReturn() error {
var e *MyErr = nil
return e // Returns non-nil interface (*MyErr, nil)
}
// badReturn() != nil is TRUE!Assigning a nil concrete pointer to an error variable and returning it instead of explicitly returning literal nil.
How does Go compiler escape analysis decide stack vs heap allocation, and how do you inspect it?
Senior Engineering Answer
During compilation, Go performs static escape analysis to prove whether a variable's lifetime can outlive its stack frame. A variable stays on the fast goroutine stack if its references never leave the function. It escapes to the heap when its pointer is returned, stored in a slice/map/global, sent over a channel, captured by a goroutine closure, exceeds stack size limits, or is boxed into an interface whose method call prevents devirtualization. You inspect escape decisions with go build -gcflags="-m -m".
type User struct{ Name string }
func stackOnly() int {
u := User{Name: "Ada"} // Stays on stack
return len(u.Name)
}
func escapesToHeap() *User {
u := User{Name: "Ada"} // Escapes to heap because pointer outlives frame
return &u
}Calling fmt.Println(x) on hot structs during benchmarks: because Println takes ...any, boxing x into an interface often forces x to escape to the heap.
How do you prevent goroutine leaks and coordinate structured cancellation with context.Context and errgroup?
Senior Engineering Answer
Goroutine leaks happen when a goroutine blocks forever on a channel send/receive, mutex, or network call without a cancellation path. Every blocking operation should select on ctx.Done() or use a buffered channel of size 1 when sending a single result from a timed-out worker so the worker can still exit if the receiver moved on. golang.org/x/sync/errgroup ties child goroutines to a shared derived context, canceling siblings immediately when any task returns a non-nil error and waiting for all goroutines to finish.
g, ctx := errgroup.WithContext(parentCtx)
for _, url := range urls {
g.Go(func() error {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil { return err }
resp, err := client.Do(req)
if err != nil { return err }
resp.Body.Close()
return nil
})
}
return g.Wait()Forgetting to call the cancel() function returned by context.WithTimeout/WithCancel via defer cancel(), which keeps timer resources and parent context references alive until the deadline expires.
How does Go's Garbage Collector work (tri-color mark-and-sweep, write barriers, and GOGC/GOMEMLIMIT)?
Senior Engineering Answer
Go uses a concurrent, non-generational, non-compacting tri-color mark-and-sweep collector. Objects are colored white (unvisited), grey (queued for scanning), or black (reachable and scanned). To let application goroutines mutate pointers concurrently during marking without missing live objects, Go enables a hybrid Dijkstra/Yuasa write barrier during the mark phase, keeping STW pauses typically under 1ms. GC pacing is tuned via GOGC (default 100, triggering GC when heap doubles over live set) and GOMEMLIMIT (Go 1.19+, soft memory ceiling preventing OOMs in containers while avoiding GC thrashing).
// Soft memory limit in Go 1.19+ prevents container OOM kills // runtime/debug.SetMemoryLimit(3500 << 20) // ~3.5 GiB
Setting GOGC=off without GOMEMLIMIT (causing OOM) or setting GOMEMLIMIT too close to the live heap size, which makes the GC run continuously and burn 100% CPU.
How does Go's sync.Mutex handle lock contention (normal mode vs starvation mode), and when can sync.RWMutex hurt performance?
Senior Engineering Answer
In normal mode, waiters sit in a FIFO queue, but a newly arriving goroutine running on a CPU can race and win the mutex ahead of a woken waiter (optimizing throughput via cache warmth). If a waiter fails to acquire the lock for more than 1ms, sync.Mutex switches to starvation mode, handing ownership strictly FIFO to the head waiter without spinning until the queue clears. Meanwhile, sync.RWMutex adds atomic counter updates on every RLock/RUnlock, causing cache-line bouncing across CPU cores; for very short critical sections under high concurrency, plain sync.Mutex can outperform RWMutex.
// Copying a sync.Mutex by value copies its internal lock state -> undefined behavior! // Pass pointers (*Service) and run `go vet` (copylocks check) in CI.
Recursive locking with sync.Mutex or sync.RWMutex: Go mutexes are non-reentrant, and calling RLock() twice while another writer is waiting for Lock() causes an immediate deadlock because RWMutex blocks new readers once a writer arrives.
How are Go generics implemented under the hood (GC shape stenciling + dictionaries), and what are their performance trade-offs?
Senior Engineering Answer
Rather than full C++-style monomorphization per type (which bloats binary size and compile times) or pure Java erasure, Go uses GC-shape stenciling. Types with the same underlying memory/pointer layout (all pointer types share one GC shape, while int, float64, and distinct structs have separate shapes) share a single compiled function body, paired with a compile-time dictionary passing type metadata and method tables. As a result, pointer-based generics incur minor indirect call overhead compared to concrete code, whereas numeric generics get specialized machine code.
type Number interface {
~int64 | ~float64
}
func Sum[T Number](vals []T) T {
var total T
for _, v := range vals {
total += v
}
return total
}Using a generic function parameter interface (T MyInterface) where a plain interface parameter suffices—or forgetting the tilde (~) in constraints like ~string, which unnecessarily rejects named types like type UserID string.
How do struct field alignment, padding, and CPU false sharing affect high-throughput Go systems?
Senior Engineering Answer
Go aligns struct fields to their natural alignment boundaries (e.g., 8 bytes for int64/pointers) and pads the struct size to a multiple of its largest alignment. Ordering fields poorly (bool, int64, bool) wastes memory on padding compared to grouping larger fields first (int64, bool, bool). At the CPU level, if two goroutines on different cores frequently write to adjacent atomic counters sitting in the same 64-byte (or 128-byte) CPU cache line, cache coherence protocols (MESI) cause false sharing, invalidating lines across cores; padding hot atomic fields by cache-line size eliminates this contention.
type PaddedCounter struct {
val atomic.Int64
_ [56]byte // Pad to 64-byte cache line to avoid false sharing
}Assuming two struct fields protected by separate atomics or mutexes cannot contend in hardware: if they share a cache line, cross-core writes still serialize at the L1/L2 cache coherence layer.
How does Go's race detector work internally, and why shouldn't you ship -race binaries to full production?
Senior Engineering Answer
Compiling with -race instruments every memory read and write at compile time using ThreadSanitizer (TSan), maintaining shadow memory and vector clocks per goroutine to detect unsynchronized concurrent accesses where at least one is a write (even if no corruption happened on that run). Because shadow memory tracking adds ~5x-10x memory overhead and ~2x-20x CPU latency, -race binaries should run in unit/integration tests, fuzzing, and optionally on a single canary instance—never across an entire latency-sensitive production fleet.
// Run full test suite with race detection and atomic coverage // go test -race -count=1 ./...
Thinking -race finds all concurrency bugs: it only detects data races along code paths actually executed during the test run, and it does not catch logical race conditions (check-then-act) protected by separate mutex acquisitions.
How do you diagnose CPU, heap, goroutine, and mutex contention bottlenecks in production using pprof and go tool trace?
Senior Engineering Answer
net/http/pprof exposes live runtime profiles: CPU profile samples call stacks at 100Hz, heap profile tracks alloc_space (allocation rate causing GC pressure) vs inuse_space (retained memory/leaks), goroutine profile reveals leaked/blocked stacks, and mutex/block profiles (enabled via runtime.SetMutexProfileFraction / SetBlockProfileRate) pinpoint lock contention. When pprof aggregates hide scheduling jitter or tail-latency pauses, runtime/trace (go tool trace) records nanosecond-level events showing goroutine scheduling delays, STW GC phases, and network-poller wakeups.
// Capture a 30-second live CPU profile over an internal admin port // go tool pprof -http=:8081 http://localhost:6060/debug/pprof/profile?seconds=30
Exposing /debug/pprof on the public HTTP mux instead of a separate localhost/internal admin listener, which leaks memory/goroutine internals and allows remote attackers to trigger expensive CPU/heap profiles.
Go (Golang) Track Coverage & Difficulty Profile
16 of 16 prompts include code examplesThis Go (Golang) preparation set groups 16 prompts across Junior (4), Mid-Level (4), Senior (4), Principal / Staff (4) roles with 4 fundamental, 4 intermediate, 4 advanced, 4 staff exercises tailored to Backend & Systems.
How do Go slices differ from arrays under the hood, and what happens when append() exceeds capacity?
What is the difference between a nil slice and an empty slice, and how does encoding/json serialize each?
How do Go maps behave under concurrent access, and why is map iteration order randomized?
How does defer work in Go, including execution order, argument evaluation timing, and named return values?
How does Go's GMP scheduler multiplex goroutines onto OS threads, including network polling and syscalls?
What are the behavioral differences between unbuffered channels, buffered channels, and nil/closed channels?
Frequently Asked Technical Interview Questions (Go (Golang))
Essential theoretical concepts, architecture trade-offs, and runtime design questions asked by hiring committees.
How does Go's GMP scheduler achieve high concurrency across OS threads?
What causes goroutine leaks and how do context deadlines prevent them?
How does Go escape analysis decide between stack and heap allocation?
Why can a Go interface holding a nil pointer evaluate as non-nil?
Pair Interview Prep with Cheat Sheets & Roadmaps
Review syntax formulas on our interactive cheat sheets, test your skills in technical quizzes, and study high-scale system designs.
Want to practice other technologies?
Explore our comprehensive technical interview tracks across all core technology stacks.